I reviewed the reference of the str.format () method again, so I made a lot of notes.
Specify the number of digits after :
. You can also specify the character alignment by inserting one of <,>, ^'between
: `and the number.
>>> '{:30}'.format('30chars') #The default is left justified
'30chars '
>>> '{:<30}'.format('left aligned') # '<'Left justified with
'left aligned '
>>> '{:>30}'.format('right aligned') # '>'Right-aligned with
' right aligned'
>>> '{:^30}'.format('centered') # '^'Centered with
' centered '
>>> '{:*^30}'.format('centered') #Fill in the blanks with the characters you placed before specifying the alignment
'***********centered***********'
>>> '{:+f}; {:+f}'.format(3.14, -3.14) # '+'Always display the sign
'+3.140000; -3.140000'
>>> '{: f}; {: f}'.format(3.14, -3.14) # ' 'If positive' 'If negative'-'Show
' 3.140000; -3.140000'
>>> '{:-f}; {:-f}'.format(3.14, -3.14) # '-'If, only the negative sign is displayed
'3.140000; -3.140000'
>>> '{:.4f}; {:.4f}'.format(3.14, -3.14) # '.'Specify the number of digits after the decimal point after
'3.1400; -3.1400'
>>> '{:,}'.format(1234567890) #Separated by commas by 3 digits
'1,234,567,890'
>>>
>>> points = 19
>>> total = 22
>>> 'Correct answers: {:.2%}'.format(points / total) #Display as a percentage
'Correct answers: 86.36%'
Specify one of d, x, o, b
after:
. Add #
to display the prefix.
symbol | Conversion destination |
---|---|
d | Decimal number |
x | Hexadecimal |
o | 8 base |
b | Binary number |
>>> 'int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}'.format(42)
'int: 42; hex: 2a; oct: 52; bin: 101010'
>>> 'int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}'.format(42)
'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'
>>> import datetime
>>> d = datetime.datetime.now()
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2016-03-17 17:33:11'
Recommended Posts