# 符号代表意义 %s -- 字符串 %10s -- 指定长度 左填充 %-10s -- 指定长度 右填充 %f -- 浮点数 %.2f -- 保留2位小数点 %d -- 整数
a = 'Name' b = 'Hider' c = 100 d = 1.80 print("My %s is %s." % (a, b)) # My Name is Hider. print("My %s is %s. And my age is %d. My height is %f." % (a, b, c, d)) # My Name is Hider. And my age is 100. My height is 1.800000.
%f
默认精度是保留后6位,可通过 %.2f
设置。
print("My %s is %s. And my age is %d. My height is %.2f." % (a, b, c, d)) # My Name is Hider. And my age is 100. My height is 1.80.
字符串长度填充。
# 左填充 print('%10s' % ('Hider')) # Hider # 右填充 print('%-10s' % ('Hider')) # Hider
f-string
直接使用变量名填充句子当中的内容。
Python 3.6
及以后版本支持 f-string
格式化输出字符串。优先推荐!!!
a = 'Name' b = 'Hider' print(f'My {a} is {b}.') # My Name is Hider. print(f'计算结果为:{2*5 + 3*10}') # 计算结果为:40 string_test = 'ABC' print(f'It\'s {string_test.lower()}') # It's abc
format
关键字用来格式化输出字符串。不同入参情况:
a = 'Name' b = 'Hider' c = 100 d = 1.80 print('My {} is {}.'.format(a,b)) # My Name is Hider.
位置默认开始从 0 计算,然后对应位置填入数据。
a = 'Name' b = 'Hider' c = 100 d = 1.80 print('My {0} is {1}. And my age is {2}.'.format(a,b,c)) # My Name is Hider. And my age is 100. print('My {1} is {2}. And my age is {0}.'.format(a,b,c)) # My Hider is 100. And my age is Name.
print('My {a} is {b}. And my age is {c}.'.format(a=10,b=20,c=30)) # My 10 is 20. And my age is 30.
dic = {'a':10, 'b':20, 'c':30} print('My {a} is {b}. And my age is {c}.'.format(**dic)) # My 10 is 20. And my age is 30.
lis = ['a','b','c'] s = 'i like {} and {} and {}.'.format(*lis) print(s) # i like a and b and c.
pi = 3.1415926535 print('{:.2f}'.format(pi)) # 3.14 print('{:+.3f}'.format(pi)) # +3.142 print('{:.2%}'.format(pi)) # 314.16%
主要用于货币数据的格式化输出。
a = 1000000000 print('{:,}'.format(a)) # 1,000,000,000 # 添加货币符号 print('${:,}'.format(a)) # $1,000,000,000
参考链接:【Python】全方面解读Python的格式化输出
参考链接:万字长文,史上最全Python字符串格式化讲解