iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 9
0

兩種風格的格式化字串

  • str.format()
    • 彈性與客製化
  • C printf style
    • 能使用的資料型態範圍相對較小

str.format()

by position or by name

fruit = ['apple', 'orange', 'watermelon']
colors = ['red', 'black', 'blue']

# by position
format_str_by_pos = '{0}, {1}, {2}'
print( format_str_by_pos.format(fruit[0], fruit[1], fruit[2]) )
print( format_str_by_pos.format(colors[1], colors[2], colors[0]) )

# by name
format_str_by_name = 'T-shirt is {t_shirt_color}; pants is {pants_color}'
print( format_str_by_name.format(t_shirt_color=colors[0], pants_color=colors[2]) )

my_color = {'t_shirt_color': 'white', 'pants_color': 'black'}
print( format_str_by_name.format(**my_color) )

# accessing arguments’ items
format_str_1 = 'T-shirt is {0[0]}; pants is {0[2]}'
print( format_str_1.format(colors) )

aligning the text

靠左、靠右、置中

# aligning the text and specifying a width
left_aligned_50 = '{:<50}'
right_aligned_50 = '{:>50}'
centered = '{:^50}'
centered_fill_dollor_sign = '{:$^50}'
print( left_aligned_50.format("python 3") )
print( right_aligned_50.format("python 3") )
print( centered.format("python 3") )
print( centered_fill_dollor_sign.format("python 3") )

其他

同數字呈現不同基底、千位數分隔號、百分比

# different bases
show_diffrent_bases = 'int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'
show_diffrent_bases_with_prefix = 'int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}'
print( show_diffrent_bases.format(42) )
print( show_diffrent_bases_with_prefix.format(42) )

# thousands separator
thousands_separator = '{:,}'
print( thousands_separator.format(5698563258) )

# percentage
percentage = '{:.3%}'
total_score = 155
score = 6
print( percentage.format( score / total_score ) )

參考


上一篇
Day8-String-stringprefix
下一篇
Day10-Dictionary-宣告
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言