在 python 中,有三种 string format: %
-format, {}
-format, $
-format
{}-format
Format String Syntax
Format strings contain replacement fields surrounded by curly braces {}
. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{
and }}
.
The grammar for a replacement field:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
arg_name ::= [identifier | integer]
attribute_name ::= identifier
element_index ::= integer | index_string
index_string ::= +
conversion ::= "r" | "s" | "a"
format_spec ::=
field_name
The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.! conversion
Three conversion flags are currently supported:!s
which calls str() on the value,!r
which calls repr() and!a
which calls ascii().format_spec
The general form of a standard format specifier is:
format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::=
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
grouping_option ::= "_" | ","
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
关于解释, 详见官方文档: Format Specification Mini-Language
str.format(*args, **kwargs)
Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}
. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
更多栗子详见 Format examples
format(value[, format_spec])
Convert a value to a “formatted” representation, as controlled by format_spec.
>>> x = 12.345
>>> format(x, '>10.2f')
' 12.35'
>>>
f-string
A formatted string literal or f-string is a string literal that is prefixed with f
or F
. These strings may contain replacement fields, which are expressions delimited by curly braces {}
. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is 'Fred'."
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is 'Fred'."
$-format
Template strings
$$
is an escape; it is replaced with a single$
.$identifier
names a substitution placeholder matching a mapping key ofidentifier
.
Examples
>>> from string import Template
>>>
>>> s = Template('$who likes $what')
>>> s.template
'$who likes $what'
>>>
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
References
- pyDoc: string
- pyDoc: Built-in Type: str.format
- pyDoc: Built-in Functions: format
- pyDoc: Lexical analysis: Formatted string literals
Read more
- Custom String Formatting
- PEP 3101 -- Advanced String Formatting
- PEP 292 -- Simpler String Substitutions
- PEP 498 -- Literal String Interpolation