Details on string formatting str.format in Python
- 2020-05-26 09:26:32
- OfStack
preface
Python added a new string formatting method in version 2.6:
str.format()
. Its basic syntax is to replace the previous %. By {} and:.
Placeholder syntax for formatting:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
"Mapping" rules
Through the position
str.format()
No more parameters can be accepted, and the positions can be in different order:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
By keyword parameter
When using key parameters, the parameter name should be provided in the string:
>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'
Through object properties
str.format()
User properties can be read directly:
>>> class User(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __str__(self):
... return "{self.name}({self.age})".format(self=self)
...
... def __repr__(self):
... return self.__str__()
...
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'
Through the subscript
The element can be accessed by subscript inside the formatted string:
>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)
Specify the conversion
You can specify the string conversion type:
conversion ::= "r" | "s" | "a"
Among them! "" r" corresponds to repr(); ! "" The corresponding str s "(); ! "" a" corresponds to ascii(). Example:
>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"
Format qualifier
Fill and align
Padding is often used along with alignment 1. ^, < , > They are centered, left-aligned, right-aligned, followed by a width, and the characters with padding after the: number can only be 1 character, if not specified, the default is to fill with space.
>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'
The floating point precision
The floating point type is represented by f, and precision control can be added in front of it:
>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'
You can also specify symbols for floating point Numbers, with a + indicating a + before a positive number and a - before a negative number. (space) means to put a space before a positive number and - before a negative number; - when nothing is added ({:f})
>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'
Specifies the base
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
0
Thousand separator
You can use "," as the thousands separator:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
1
Percent display
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
2
In fact, format also supports more type symbols:
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Other skills
Placeholders are nested
Sometimes placeholder nesting is useful:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
4
Use as a function
Instead of specifying the formatting parameter, you can call it as a function where you don't want it:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
5
Escape curly braces
When you need braces in a string, you can escape them with braces:
>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'
6
conclusion