美文网首页
str.format [cheat sheet]

str.format [cheat sheet]

作者: import_hello | 来源:发表于2018-12-15 01:44 被阅读0次

转载须注明出处:简书@Orca_J35 | GitHub@orca-j35,所有笔记均托管于 python_notes 仓库
参考:https://kapeli.com/cheat_sheets/Python_Format_Strings.docset/Contents/Resources/Documents/index

Field Width and Alignment

Format Feature
'hey {:10}'.format('hello') Specify width (Aign left, fill with spaces)
'{:010}'.format(2) Fill with zeroes<br />Output: 0000000002
'{:*^30}'.format('text') Specify width, align to center<br />Output: *************text*************

Member and Element Access

Format Feature
'{0}, {1}, {2}'.format(1, 2, 3) Access arguments by ordinal position<br />Output: 1, 2, 3
'{}, {}, {}'.format(1, 2, 3) Implicit positional arguments (2.7 and above only)<br />Output: 1, 2, 3
'{value1}, {value2}, {value2}'.format(value1=1, value2=2, value3=3) Access keyword arguments by name<br />Output: 1, 2, 2
'{[1]}'.format(['first', 'second', 'third']) Access element by index<br />Output: second
'{.name}'.format(sys.stdin) Access element attribute<br />Output: <stdin>
'{[name]}'.format({'name': 'something'}) Access element by key<br />Output: something

Numerical Representation

Format Feature
'{:x}'.format(100) Hexadecimal representationOutput: 64
'{:X}'.format(3487) Hexadecimal representation (uppercase letters)<br />Output: D9F
'{:#x}'.format(100) Hexadecimal representation (including the 0x)<br />Output: 0x64
'{:b}'.format(100) Binary representation<br />Output: 1100100
'{:c}'.format(100) Character representation<br />Output: d
'{:d}'.format(100) Decimal representation (default)<br />Output: 100
'{:,}'.format(1000000) With thousands separator<br />Output: 1,000,000
'{:o}'.format(100) Octal representation<br />Output: 144
'{:n}'.format(100) Like d, but uses locale information for separators<br />Output: 100
'{:e}'.format(0.0000000001) Exponent notation<br />Output: 1.000000e-10
'{:E}'.format(0.0000000001) Exponent notation (capital 'E')<br />Output: 1.000000E-10
'{:f}'.format(3/14.0) Fixed point<br />Output: 0.214286
'{:g}'.format(3/14.0) General format<br />Output: 0.214286
'{:%}'.format(0.66) Percentage<br />Output: 66.000000%
'{:.3}'.format(0.214286) Precision<br />Output: 0.214

Conversions

Format Feature
'{!r}'.format('string') Calling repr on arguments<br />Output: 'string'
'{!s}'.format(1.53438987) Calling str on arguments<br />Output: 1.53438987

相关文章

网友评论

      本文标题:str.format [cheat sheet]

      本文链接:https://www.haomeiwen.com/subject/guhohqtx.html