Home > Backend Development > Python Tutorial > What does python string formatting mean?

What does python string formatting mean?

步履不停
Release: 2019-07-29 09:27:08
Original
9005 people have browsed it

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'
Copy after login

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'
Copy after login

3. Filling and formatting

:[Filling character][Alignment<^>] [Width]

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

4. Precision and base

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

5. Using index

>>> li
[&#39;hoho&#39;, 18]
>>> &#39;name is {0[0]} age is {0[1]}&#39;.format(li)
&#39;name is hoho age is 18
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template