Home  >  Article  >  Backend Development  >  What does python string formatting mean?

What does python string formatting mean?

步履不停
步履不停Original
2019-07-02 14:48:018978browse

What does python string formatting mean?

Python string formatting means using the format function to format a string.

Usage: It uses {} and: to replace the traditional % method.

1. Use positional parameters

Key points: From the following example, we can see that positional parameters are not subject to order constraints and can be {}, as long as there are corresponding parameter values ​​in the format. The parameter index starts from 0, and the incoming positional parameter list can be *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 parameters

Key points: the keyword parameter values ​​must match, and a dictionary can be used as a keyword parameter To pass in the value, just add ** in front of the dictionary

>>> 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. Filling and formatting

:[Filling character][Alignment59aec9514828c418325a37f5a912e1ee] [Width]

>>> '{0:*>10}'.format(10)  ##右对齐
'********10'
>>> &#39;{0:*<10}&#39;.format(10)  ##左对齐
&#39;10********&#39;
>>> &#39;{0:*^10}&#39;.format(10)  ##居中对齐
&#39;****10****&#39;

4. Precision and base

>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10)    #二进制
'1010'
>>> '{0:o}'.format(10)     #八进制
'12'
>>> '{0:x}'.format(10)     #16进制
'a'
>>> '{:,}'.format(12369132698)  #千分位格式化
'12,369,132,698'

5. Using index

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18

Related tutorial recommendations: Python video tutorial

The above is the detailed content of What does python string formatting mean?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn