Python: format()

In Python3, using format() for string formatting is standard instead using traditional “%” formatting.

'FOO{0}BAR'.format(10)
>>'FOO10BAR'

# parameters can be indexed or named
'FOO{0}{1}{2}BAR'.format('a', 'b', 'c')
>>'FOOabcBAR'
'FOO{a}{b}{c}BAR'.format(a=1, b=2, c=3)
>>'FOO123BAR'

# with separater
'FOO{0:,d}BAR'.format(1000000)
>>'FOO1,000,000BAR'

https://docs.python.org/2.7/library/stdtypes.html#str.format

>This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code.

Leave a Reply

Your email address will not be published. Required fields are marked *