1,格式化字符串
- {var} 作为占位符
Year = 2020f 'Today is {Year}'# f.'my py coding... {var}' F.'my py coding {var}''the sum of 1 + 2 is {0}'.format(1+2)
- 百分数,小数的格式化
def test_f():import mathprint(f'{math.pi:0.2f}') # 保持小数点后两位test_f()def test_format():print('{:}'.format(99)) # : 可以作为占位符print('{:5}'.format(99)) # 让99的字符宽度为5print('{:0.1%}'.format(0.3)) # 保留百分数后一位小数test_format()'''
3.14
9999
30.0%
'''
- :加数字用于对齐
def test_tidy():D = {'name': 'jack', 'age': 19, 'gender': 'male'}for k, v in D.items():print('{0:10} ==> {1}'.format(k, v))'''
name ==> jack
age ==> 19
gender ==> male
'''
- !a !r !s 转化为字符串后输出
>>> var = 'sexy'
>>> print(f'She is so {var}.')
She is so sexy.
>>> print(f'She is so {var!s}.')
She is so sexy.
>>> print(f'She is so {var!r}.')
She is so 'sexy'.
2,str() 和 repr()
str(obj) 返回可读字符串,repr(obj)返回机器可读的表示,两者对于/或者\都不会转义,将对象转换为字符串。
>>> list = ['i', 'dare', 'you']
>>> str(list)
"['i', 'dare', 'you']"
>>> repr(list)
"['i', 'dare', 'you']"
3,string.format()方法的详细版本
- 用{}占位符
'hello, {}'.format('world')
- 用{index} index可以调换位置
'hello, {0}, {1}'.format('world', 'python')
- 关键字参数 {argument}
>>> 'hello, {world}, {python}'.format(world='world', python='python')'hello, world, python'
- 位置和关键字参数可任意组合
'I\'m {0}, age {1}, come from {country}'.format('Lee', 19, country='China')>>> 'I\'m {0}, age {1}, come from {country}'.format('Lee', 19, country='China')"I'm Lee, age 19, come from China">>>
- 用**代表修饰字典参数
>>> table{'a': 100, 'b': 200, 'c': 300}>>> 'a: {a}, b: {b}, c: {c}'.format(**table)'a: 100, b: 200, c: 300'>>>
- 用名称访问集合
>>> D = {'name': 'jack', 'age': 19, 'gender': 'male'}
>>> print('name: {[name]}'.format(D))
name: jack
- 练习
>>> for i in range(1, 11):
... print(f'{i:2}, {i*i:3}, {i*i*i:4}')
... 1, 1, 12, 4, 83, 9, 274, 16, 645, 25, 1256, 36, 2167, 49, 3438, 64, 5129, 81, 729
10, 100, 1000
4,手动格式字符串
# rjust(talbe_num) 用于相对位置空格>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
... 1 1 12 4 83 9 274 16 645 25 1256 36 2167 49 3438 64 5129 81 729
10 100 1000
字符串对象的 str.rjust() 方法通过在左侧填充空格来对给定宽度的字段中的字符串进行右对齐。
类似的方法还有 str.ljust() 和 str.center() 。
这些方法不会写入任何东西,它们只是返回一个新的字符串,
如果输入的字符串太长,它们不会截断字符串,而是原样返回.