1 >>> print('{} {}'.format('hello','world')) # 不带字段
2 hello world
3 >>> print('{0} {1}'.format('hello','world')) # 带数字编号
4 hello world
5 >>> print('{0} {1} {0}'.format('hello','world')) # 打乱顺序
6 hello world hello
7 >>> print('{1} {1} {0}'.format('hello','world'))
8 world world hello
9 >>> print('{a} {tom} {a}'.format(tom='hello',a='world')) # 带关键字
10 world hello world
2、进阶用法
(1)< (默认)左对齐、> 右对齐、^ 中间对齐、= (只用于数字)在小数点后进行补齐
(2)取位数“{:4s}”、”{:.2f}”等
1 >>> print('{} and {}'.format('hello','world')) # 默认左对齐
2 hello and world
3 >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐
4 hello and world
5 >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐
6 hello and world
7 >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
8 1.123 is 1.12
9 >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
10 1.123 is 1.12
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
... 'and the imaginary part {0.imag}.').format(c)
'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'
>>>
>>> for align, text in zip('<^>', ['left', 'center', 'right']):
... '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16) # 官方文档给出来的,无法在IDLE复现
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
... for base in 'dXob':
... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
... print()
...
5 5 5 101
6 6 6 110
7 7 7 111
8 8 10 1000
9 9 11 1001
10 A 12 1010
11 B 13 1011
另,可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:
name = 'jack'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99
print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')
# 结果
my name is Jack.
I am ****18**** years old.
I am a man
My salary is 9999.990