目前Python格式化字符串的方式有三种:
1. %
2.format
3.f-string
% 格式化常用方法:
# % 格式化字符串 s1 = 'name is %s' % ('zhangsan') # >>> name is zhangsan # % 格式化整数 s2 = 'age is %d' % (12) # >>> age is 12 # % 格式化整数,指定位数,用0填充 s3 = 'today is %02d' % (8) # >>> today is 08 # % 格式化浮点数,默认保留6位小数 s4 = 'PI = %f' % (3.1415) # >>> PI = 3.141500 # % 格式化浮点数,保留2位小数 s5 = 'PI = %.2f' % (3.1415) # >>> PI = 3.14 # % 格式化浮点数,不带小数 s6 = 'PI = %.0f' % (3.1415) # >>> PI = 3
format 格式化常用方法:
# format 格式化字符串 s1 = 'name is {}'.format('zhangsan') # >>> name is zhangsan # format 格式化整数 s2 = 'age is {}'.format(12) # >>> age is 12 # format 格式化整数,指定位数,用0填充 s3 = 'today is {:0>3d}'.format(8) # >>> today is 008 # format 格式化整数,以逗号分隔 s4 = 'number is {:,}'.format(123456789) # >>> number is 123,456,789 # format 格式化整数,指数记法 s5 = 'number is {:.2e}'.format(123456789) # >>> number is 1.23e+08 # format 格式化浮点数 s6 = 'PI = {}'.format(3.1415) # >>> PI = 3.1415 # format 格式化浮点数,保留2位小数 s7 = 'PI = {:.2f}'.format(3.1415) # >>> PI = 3.14 # format 格式化浮点数,带符号保留两位小数 s8 = 'PI = {:+.2f}'.format(-3.1415) # >>> PI = -3.14 # format 格式化浮点数,百分比显示 s9 = 'number is {:.2%}'.format(3.1415) # >>> number is 314.15% # format 格式化浮点数,不带小数 s10 = 'PI = {:.0f}'.format(3.1415) # >>> PI = 3
f-string 格式化常用方法:
data1 = 'zhangsan' data2 = 123456789 data3 = 3.1415 # f 格式化字符串 s1 = f'name is {data1}' # >>> name is zhangsan # f 格式化整数 s2 = f'number is {data2}' # >>> number is 12 # f 格式化整数,指定位数,用0填充 s3 = f'number is {data2:010d}' # >>> number is 0123456789 # f 格式化浮点数 s4 = f'PI = {data3}' # >>> PI = 3.1415 # f 格式化浮点数,保留2位小数 s5 = f'PI = {data3:.2f}' # >>> PI = 3.14 # f 格式化浮点数,不带小数 s6 = f'PI = {data3:.0f}' # >>> PI = 3
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279023.html