Read Catalogue
- Grammar
- By location
- by keyword
- Through object properties
- by subscript
- Fill and align
- Accuracy and type F
- In-process conversion
- Thousands separator
Python since 2.6, a new format string function Str.format (), powerful, can replace the original%
Note : The following operating version is python2.7
Mapping example back to top syntax
by {} and: replace%
Back to top through position
>>> ' {0} was {1} '. Format (' Jihite ', ' 4 years old ') ' Jihite are 4 years old ' >>> ' {0} is {1} {0} '. Format (' Jihi Te ', ' 4 years old ') ' Jihite are 4 years old Jihite '
The Format function allows you to accept unlimited number of arguments, unlimited order
Back to top by keyword
>>> ' {name}:{age} '. Format (age=4,name= ' jihite ') ' jihite:4 ' >>> ' {name}:{age} '. Format (age=4,name= ' Jihite ', locate= ' Beijing ') ' Jihite:4 '
Use = To assign a value to a variable in format parentheses
Back to top through object properties
>>> class Person: ... def __init__ (self, Name, age): ... Self.name,self.age = name, age ... def __func__ (self): ... Return "This guy is {self.name}, was {self.age} old". Format (self=self) ... >>> s =person (' Jihite ', 4) >>> s . __func__ () ' This guy is Jihite, was 4 old '
Go back to the top by subscript
>>> ' {0[0]} is {0[1]} years old! '. Format ([' Jihite ', 4]) ' Jihite is 4 years old! ' >>> ' {0} is {1} years old! '. Format (' Jihite ', 4) ' Jihite is 4 years old! '
is actually through the location
Format qualifier
Through {}: symbol
Back to top fill and align
^<> are centered, left-aligned, right-aligned, followed by width
>>> ' {: >10} '. Format (' jihite ') ' jihite ' >>> ' {: <10} '. Format (' jihite ') ' Jihite ' > >> ' {: ^10} '. Format (' jihite ') ' jihite '
Back to top precision and type F
Accuracy is often used in conjunction with F
>>> ' {:. 2f} '. Format (3.1415) ' 3.14 ' >>> ' {:. 4f} '. Format (3.1) ' 3.1000 '
Back to top of the system conversion
>>> ' {: b} '. Format (Ten) ' 1010 ' >>> ' {: o} '. Format (Ten) ' >>> ' {:d} '. Format (Ten) ' >> > ' {: x} '. Format (Ten) ' A '
where b o D x indicates two or eight, 16 or 16 binary respectively
Back to top thousand separators
>>> ' {:,} '. Format (1000000) ' 1,000,000 '
>>> ' {:,} '. Format (100000.23433)
' 100,000.23433 '
>>> ' {:,} '. Format (' Abcedef ') Traceback (most recent call last): File "<stdin>", line 1, in <module& Gt Valueerror:cannot specify ', ' with ' s '.
This situation is only for digital
Python small white (no programming basis, no computer basis) development of the road Auxiliary Knowledge 4. Format