RTRT
刚才在格式化字符串,遇到了这样的一种字符串(HTML样式):
- @list l0:level5
- {mso-level-number-format:alpha-lower;
- mso-level-text:"%5\)";
- mso-level-tab-stop:none;
- mso-level-number-position:left;
- margin-left:105.0pt;
- text-indent:-21.0pt;}
复制代码众所周知,Python有三种格式化字符串的方式:
- 1. %-formatting格式化字符串
- 最早的格式化是用%(百分号), 它这么用:
- In : name = 'World'
- In : id = '10'
- In : 'Hello %s,id=%s' %(name,id)
- Out: 'Hello World,id=10'
- 这里用的%s表示格式化成字符串,另外常用的是%d(十进制整数)、%f(浮点数)。
- 另外也支持使用字典的形式:
- In : 'Hello[%(name)s],id=%(name)s' % {'id': 10, 'name': 'World'}
- Hello[World],id=10
- 2. str.format()格式化字符串
- 常规用法
- In : name = 'World'
- In : 'Hello {}' %(name)
- Out: 'Hello World'
- 通过位置访问:
- In : '{2}, {1}, {0}'.format('a', 'b', 'c')
- Out: 'c, b, a'
- 通过关键字访问:
- In : 'Hello {name}'.format(name='testerzhang')
- Out: 'Hello testerzhang'
- 3. f-string格式化字符串
- Python3.6 版本开始出现了此新的格式化字符串,性能又优于前面两种方式。
- In : name = "testerzhang"
- In : print(f'Hello {name}.')
- In : print(f'Hello {name.upper()}.')
- Out: Hello testerzhang.
- Out: Hello TESTERZHANG.
- In : d = {'id': 1, 'name': 'testerzhang'}
- In : print(f'User[{d["id"]}]: {d["name"]}')
- Out: User[1]: testerzhang
- 注意:如果低于Python3.6,可以通过pip install future-fstrings即可,在相应的py 文件里不需要加import这个库,但是需要头部加上# coding: future_fstrings。
复制代码因为里面带{}、%,所以采用方法1、2都失败了。想知道有什么办法可以格式化字符串吗?