Detailed format function Python--

Foreword

  • string format for formatting function

usage

  • The basic syntax of symbolic representations of operations by {},
  • And each sequence can be set {},
  • Respectively correspond to the order of format parameters,
  • If no subscript {}, 0 default weight increments.

By location

print('{0} {1}'.format('hello','world')) # 通过位置
print('{1} {0}'.format('hello','world'))

Here Insert Picture Description

By Keyword

print('{人物}今天{事件}'.format(人物='我',事件='写博客'))#通过关键字
job = {'person':'你','affair':'写博客'}
# 可用字典当关键字传入值时,在字典前加**即可
print('{person}昨天{affair}'.format(**job))

Here Insert Picture Description

Filling aligned

^ < > Denote centered, left justified, right justified, the width of the back

print('{:^18}'.format('hello'))
print('{:>18}'.format('hello'))
print('{:<18}'.format('hello'))
print('{:*<18}'.format('hello'))
print('{:&>18}'.format('hello'))

Here Insert Picture Description

Accuracy and type f

print('{:.1f}'.format(3.1415926))
print('{:.3f}'.format(3.1))

Here Insert Picture Description

Decimal conversion

symbol description
b Binary
O Octal
d Decimal
x Hex
print('{:b}'.format(777))
print('{:o}'.format(777))
print('{:d}'.format(777))
print('{:x}'.format(777))

Here Insert Picture Description

Thousands Separator

  • Usually used as money
print('{:,}'.format(100000000))
print('{:,}'.format(12345.6789))

Here Insert Picture Description

Published 29 original articles · won praise 19 · views 1308

Guess you like

Origin blog.csdn.net/s1156605343/article/details/104846523