formatting
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.format(*args, **kwargs) Parameters
| Parameter | Purpose |
|---|---|
| {} | positional/auto-numbered field |
| {0} | explicit positional index |
| {name} | keyword field |
| {:spec} | format spec, e.g. '.2f', '>10', ',' |
Examples
>>> 'Hello, {}!'.format('world')
'Hello, world!' positional field
>>> '{name} is {age}'.format(name='Ada', age=36)
'Ada is 36' keyword fields
>>> 'pi = {:.2f}'.format(3.14159)
'pi = 3.14' format spec: fixed-point to 2 decimals
'{:>11,}'.format(1234567) ' 1,234,567' — right-aligned in an 11-char field with comma thousands separator. If the width is less than the formatted length, Python does not truncate and no padding is added.
Gotcha
f-strings (f'...') are faster and clearer for literal templates but evaluate at definition time; str.format() is the right tool for templates loaded from files or i18n catalogs. Escape a literal brace by doubling it: {{ or }}.
Related methods
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.
str.zfill
Returns a copy padded on the left with '0' digits to reach the given width. Unlike rjust('0'), it preserves a leading sign ('+' or '-') by placing the zeros after it.
str.join
Returns a string built by concatenating every string in the iterable, separated by the string on which join is called. Every element of the iterable must be a str, or TypeError is raised.
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.