参考
python的输出方式很多,这里整理一下
普通输出
x = 100 print(x) print('hello, world','qxd')
100 hello, world qxd
|
{}用法
print('{} {}'.format('hello','world')) hello world
print('{0} {1}'.format('hello','world')) hello world
print('{0} {1} {0}'.format('hello','world')) hello world hello
print('{1} {1} {0}'.format('hello','world')) world world hello
print('{a} {tom} {a}'.format(tom='hello',a='world')) world hello world
coord = {'latitude': '37.24N', 'longitude': '-115.81W'} print('Coordinates: {latitude}, {longitude}'.format(**coord)) 'Coordinates: 37.24N, -115.81W'
'Point({self.x}, {self.y})'.format(self=self)
|
格式转换
0表示format中的位置,一个不写也可以
print('{0:b}'.format(3)) 11
print('{:c}'.format(20))
print('{:d}'.format(20)) 20
print('{:o}'.format(20)) 24
print('{:x}'.format(20)) 14
print('{:e}'.format(20)) 2.000000e+01
print('{:g}'.format(20.1)) 20.1
print('{:f}'.format(20)) 20.000000
print('{:n}'.format(20)) 20
print('{:%}'.format(20)) 2000.000000%
print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42)) 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
|
左中右对齐,位数补全
print('{} and {}'.format('hello','world')) hello and world
print('{:10s} and {:>10s}'.format('hello','world')) hello and world
print('{:^10s} and {:^10s}'.format('hello','world')) hello and world
print('{} is {:.2f}'.format(1.123,1.123)) 1.123 is 1.12
print('{0} is {0:>10.2f}'.format(1.123)) 1.123 is 1.12
print('{:<30}'.format('left aligned')) 'left aligned '
print('{:>30}'.format('right aligned')) ' right aligned'
print('{:^30}'.format('centered')) ' centered '
print('{:*^30}'.format('centered')) '***********centered***********'
print('{:0=30}'.format(11)) '000000000000000000000000000011'
|
正负号显示
>>> '{:+f}; {:+f}'.format(3.14, -3.14) '+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) ' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) '3.140000; -3.140000'
正负符号显示 %+f, %-f, 和 % f的用法
|
时间
>>> import datetime >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58) >>> '{:%Y-%m-%d %H:%M:%S}'.format(d) '2010-07-04 12:15:58'
|
表示金钱
>>> '{:,}'.format(1234567890) '1,234,567,890'
|
输出表格
表示占位符可以嵌套
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-string
"{0} {1}".format("hello","world") 'hello world'
a = "hello" b = "world" f"{a} {b}" print('hello world')
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
|
s-string和r-string
https://blog.csdn.net/weixin_42165585/article/details/80980739