|
Python substring format
usage:
{} And through: to replace the traditional way%
1, using the positional parameters
IMPORTANT: The following examples can be seen from the location parameter is not bound by the order and for {}, has long format parameter corresponding to the value of the parameter index from 0 to open a list of available parameters passed in location list *
>>> Li = [ 'hoho', 18]
>>> 'My name is {}, age {}'. Format ( 'hoho', 18)
'My name is hoho, age 18'
>>> 'My name is {1}, age {0}'. Format (10, 'hoho')
'My name is hoho, age 10'
>>> 'My name is {1}, age {0} {1}'. Format (10, 'hoho')
'My name is hoho, age 10 hoho'
>>> 'My name is {}, age {}'. Format (* li)
'My name is hoho, age 18'
2. Use keyword arguments
IMPORTANT: To get keywords value, the dictionary can be used as keyword argument values passed, the dictionary can be preceded by **
>>> Hash = { 'name': 'hoho', 'age': 18}
>>> 'My name is {name}, age is {age}'. Format (name = 'hoho', age = 19)
'My name is hoho, age is 19'
>>> 'My name is {name}, age is {age}'. Format (** hash)
'My name is hoho, age is 18'
3, filled with formatting
: [Fill characters] [Alignment < ^ >] [width]
>>> '{0: *> 10}'. Format (10) ## right-aligned
'******** 10'
>>> '{0: * <10}'. Format (10) ## Left
'10 ******** '
>>> '{0: * ^ 10}'. Format (10) ## centered
'**** 10 ****'
4, accuracy and hexadecimal
>>> '{0: .2f}'. Format (1/3)
'0.33'
>>> '{0: b}'. Format (10) # Binary
'1010'
>>> '{0: o}'. Format (10) # octal
'12'
>>> '{0: x}'. Format (10) # 16 hex
'A'
>>> '{:,}'. Format (12369132698) # thousands formatting
'12, 369,132,698 '
5, use the index
>>> Li
[ 'Hoho', 18]
>>> 'Name is {0 [0]} age is {0 [1]}'. Format (li)
'Name is hoho age is 18 |
|
|
|