String Method format in Python: String Formatting
Returns a formatted copy of a string.
format(args, *kwargs)
args-- positional argumentskwargs-- named arguments
The string on which this method is called can contain placeholders in curly braces {}, which are replaced. Regular text outside the braces remains unchanged.
The method returns a copy of the string where placeholders are replaced with text values from the passed arguments. A placeholder is either the name of an argument or its index. If numbers are used and they form a sequence (0, 1, 2, ...), they can be omitted altogether (but not selectively). For example, {}-{}-{} and {0}-{1}-{2} are equivalent.
'{}-{}-{}'.format(1, 2, 3) # Result: '1-2-3'
'{}-{}-{}'.format(*[1, 2, 3]) # Result: '1-2-3'
'{one}-{two}-{three}'.format(two=2, one=1, three=3) # Result: '1-2-3'
'{one}-{two}-{three}'.format(**{'two': 2, 'one': 1, 'three': 3}) # Result: '1-2-3'
After the name, any number of attribute access or index addressing expressions can follow. An object’s attribute is accessed using a dot ., and an element is accessed using square brackets [].
import datetime
obj = {'one': {'sub': 1}, 'two': [10, 2, 30], 'three': datetime.datetime.now()}
'{one[sub]}-{two[1]}-{three.year}'.format(**obj)
Casting is used for type conversion before formatting.
Usually, the return of the formatted value is handled by the __format__() method, but there are cases where forced conversion is required, for example, to a string, bypassing the existing implementation. The default formatting logic is bypassed by converting the value to a string before calling __format__().
Three conversion flags are supported: !s calls str(), !r calls repr(), !a calls ascii().
import datetime
demo = datetime.date.today()
result = '{!s}, {!r}, {!a}, {}'.format(demo, demo, demo, demo)
print(result)
The format includes a definition of how the value should be represented, including information about length, alignment, string padding, precision for numbers, and so on.
You can specify field width and alignment:
right = 'Start{0:20}End'.format(7)
left = 'Start{0:<20}End'.format(8)
center = 'Start{0:^20}End'.format(9)
print(right)
print(left)
print(center)
Result
Start 7End
Start8 End
Start 9 End
Displaying Floating Point Numbers
print('{0}'.format(4/3))
print('{0:f}'.format(4/3))
print('{0:.2f}'.format(4/3))
print('{0:10.3f}'.format(4/3))
Result
1.3333333333333333
1.333333
1.33
1.333