目前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 格式化字符串 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
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