English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Preface
Python in 2.6 A new string formatting method has been added in the new version: str.format(). Its basic syntax is to use {} and : to replace the % of the previous version.
The placeholder syntax for formatting:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
The "mapping" rule
Through position
The str.format() method can accept an unlimited number of parameters, and the positions do not have to be in order:
>>> "{0} {1}.format("hello", "world") 'hello world' >>> "{0} {1}".format("hello", "world") 'hello world' >>> "{1} {0} {1}.format("hello", "world") 'world hello world'
Through keyword arguments
When using keyword arguments, the parameter name must 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() can directly read user properties:
>>> 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'
By index
You can access elements inside a string that needs to be formatted using indices:
>>> 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 conversion
You can specify the type of string conversion:
conversion ::= "r" | "s" | "a"
Among them, "!r" corresponds to repr(); "!s" corresponds to str(); "!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 specifiers
Filling and alignment
Filling is often used together with alignment. ^, <, > represent center alignment, left alignment, and right alignment respectively. The width follows after these symbols, and the character for filling follows the : symbol. If not specified, the default is to fill with spaces.
>>> "{:>}8".format("181716") ' 181716' >>> "{:08".format("181716") "00181716' >>> "{:->8".format("181716") '--181716' >>> "{:-<8".format("181716") '181716--' >>> "{:-^8".format("181716") '-181716-' >>> "{:-<25}>".format("Here ") "Here --------------------"
Floating-point precision
Use f to represent floating-point types, and you can add precision control before 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 a sign for floating-point numbers:+ Means displaying before positive numbers +Display before negative numbers -; (space) means adding a space before positive numbers and adding -;- It is consistent with nothing 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'
Specify the base
>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18) "int:", 18; hex: 12; oct: 22; bin: 10010' >>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18) "int:", 18; hex: 0x12; oct: 0o22; bin: 0b10010'
Thousand separator
You can use "," as a thousand separator:
>>> "'{:,}".format(123456789) '1,234,567,890
Percentage display
>>> "progress: {:.2%".format(19.88/22) "progress:", 9'36%
In fact, format also supports more type specifiers:
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Other tricks
Nested placeholders
Sometimes, nested placeholders can still be very useful:
>>> "'{0:{fill}{align}"16}'.format("hello", fill='*', align='^') '*****hello******' >>> >>> for num in range(5,12) ... for base in "dXob": ... print("{0:{width}{base}}".format(num, base=base, width=}}5), end=' ') ... print() ... ... 5 5 5 101 6 6 6 110 7 7 7 111 8 8 10 1000 9 9 11 1001 10 A 12 1010 11 B 13 1011
Use as a Function
You can first not specify the formatting parameters and call it as a function where it is not needed:
>>> email_f = "Your email address was {email}".format >>> print(email_f(email="[email protected]")) Your email address was [email protected]
Escape Curly Braces
When brackets are needed in a string, they can be escaped using curly braces:
>>> "The {} set is often represented as {{0}}".format("empty") 'The empty set is often represented as {0}'
Summary
That's all for this article. I hope the content of this article can bring some help to everyone's learning or work. If you have any questions, you can leave messages for communication. Thank you for your support of the Yell Tutorial.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been edited by humans, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.