a = 0b10111010b = 0xc5cprint('二進制:%d, 十六進程:%d' % (a, b))
二進制:186, 十六進程:3164
key = 'my_key'value = 1.234formatted = '%-10s = %.2f' % (key, value)print(formatted)
my_key = 1.23
key = 1.234value = 'my_key'formatted = '%-10s = %.2f' % (key, value)print(formatted)
Traceback (most recent call last): File "/python/format.py", line 12, in <module> formatted = '%-10s = %.2f' % (key, value)TypeError: must be real number, not str
formatted = '%-10s = %.2f' % (key, value)
pantry = [ ('avocados', 1.25), ('bananas', 2.5), ('cherries', 15),]for i, (item, count) in enumerate(pantry): print('#%d: %-10s = %.2f' % (i, item, count))
#0: avocados = 1.25#1: bananas = 2.50#2: cherries = 15.00
for i, (item, count) in enumerate(pantry): print('#%d: %-10s = %d' % ( i + 1, item.title(), round(count)))
#1: Avocados = 1#2: Bananas = 2#3: Cherries = 15
template = '%s loves food. See %s cook.'name = 'Max'formatted = template % (name, name)print(formatted)
Max loves food. See Max cook.
old_way = '%-10s , %.2f, %-8s' % (key, value,key) # 重複指定key
new_way = '%(key)-10s , %(value).2f, %(key)-8s' % { 'key': key, 'value': value} # 只須要指定一次key
print(old_way)print(new_way)
key1 , 1.13, key1 key1 , 1.13, key1
for i, (item, count) in enumerate(pantry): before = '#%d: %-10s = %d' % ( i + 1, item.title(), round(count))
after = '#%(loop)d: %(item)-10s = %(count)d' % { 'loop': i + 1, 'item': item.title(), 'count': round(count), }
assert before == after
soup = 'lentil'formatted = 'Today\'s soup is %(soup)s.' % {'soup': soup} # 這裏再次指定了變量soupprint(formatted)
Today's soup is lentil.
menu = { 'soup': 'lentil', 'oyster': 'kumamoto', 'special': 'schnitzel',}template = ('Today\'s soup is %(soup)s, ' 'buy one get two %(oyster)s oysters, ' 'and our special entrée is %(special)s.')formatted = template % menuprint(formatted)
Today's soup is lentil, buy one get two kumamoto oysters, and our special entrée is schnitzel.
a = 1234.5678formatted = format(a, ',.2f')print(formatted)
b = 'my string'formatted = format(b, '^20s') # 居中顯示字符串print('*', formatted, '*')
1,234.57* my string *
key = 'my_var'value = 1.234
formatted = '{} = {}'.format(key, value)print(formatted)
my_var = 1.234
formatted = '{:<10} = {:.2f}'.format(key, value)print(formatted)
my_var = 1.23
print('%.2f%%' % 12.5)print('{} replaces {{}}'.format(1.23))
12.50%1.23 replaces {}
formatted = '{1} = {0}'.format(key, value)print(formatted)
1.234 = my_var
formatted = '{0} loves food. See {0} cook.'.format(name)print(formatted)
Max loves food. See Max cook.
for i, (item, count) in enumerate(pantry): old_style = '#%d: %-10s = %d' % ( i + 1, item.title(), round(count)) new_style = '#{}: {:<10s} = {}'.format( i + 1, item.title(), round(count))
assert old_style == new_style
formatted = 'First letter is {menu[oyster][0]!r}'.format( menu=menu)print(formatted)
First letter is 'k'
old_template = ( 'Today\'s soup is %(soup)s, ' 'buy one get two %(oyster)s oysters, ' 'and our special entrée is %(special)s.')old_formatted = template % { 'soup': 'lentil', 'oyster': 'kumamoto', 'special': 'schnitzel',}
new_template = ( 'Today\'s soup is {soup}, ' 'buy one get two {oyster} oysters, ' 'and our special entrée is {special}.')new_formatted = new_template.format( soup='lentil', oyster='kumamoto', special='schnitzel',)assert old_formatted == new_formatted
key = 'my_var'value = 1.234
formatted = f'{key} = {value}'print(formatted)
my_var = 1.234
formatted = f'{key!r:<10} = {value:.2f}'print(formatted)
'my_var' = 1.23
f_string = f'{key:<10} = {value:.2f}'
c_tuple = '%-10s = %.2f' % (key, value)
str_args = '{:<10} = {:.2f}'.format(key, value)
str_kw = '{key:<10} = {value:.2f}'.format(key=key, value=value)
c_dict = '%(key)-10s = %(value).2f' % {'key': key, 'value': value}
print(f'f_string:{f_string}')print(f'c_tuple:{c_tuple}')print(f'str_args:{str_args}')print(f'str_kw:{str_kw}')print(f'c_dict:{c_dict}')
f_string:my_var = 1.23c_tuple:my_var = 1.23str_args:my_var = 1.23str_kw:my_var = 1.23c_dict:my_var = 1.23
for i, (item, count) in enumerate(pantry): old_style = '#%d: %-10s = %d' % ( i + 1, item.title(), round(count))
new_style = '#{}: {:<10s} = {}'.format( i + 1, item.title(), round(count))
f_string = f'#{i+1}: {item.title():<10s} = {round(count)}'
assert old_style == new_style == f_string
for i, (item, count) in enumerate(pantry): print(f'#{i+1}: '
f'{item.title():<10s} = ' f'{round(count)}')
#1: Avocados = 1#2: Bananas = 2#3: Cherries = 15
places = 3number = 1.23456print(f'My number is {number:.{places}f}')
本文分享自微信公衆號 - 極客起源(geekculture)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。javascript