Home > Backend Development > Python Tutorial > Detailed introduction to format() format output in Python (with code)

Detailed introduction to format() format output in Python (with code)

不言
Release: 2019-04-15 11:19:18
forward
4080 people have browsed it

This article brings you a detailed introduction to format() format output in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Formatted output: format()

format(): Replace the traditional % with {} to achieve formatted output

1. Use positional parameters: that is, In the string, replace the variable value that needs to be output with {}, and then use format() to modify it to become the desired string. The positional parameter is to change the traditional % to {}, and automatically replace it according to the positional order.

'My name is {},age:{}'.format('Anxc',18)
'My name is Anxc,age:18'
Copy after login

2. Use positional parameters: On the original basis, the replacement value is changed according to the position by changing the position (I feel it is useless, not as useful as the first one)

'My name is {1},age:{0}'.format(18,'Anxc')
'My name is Anxc,age:18'
Copy after login

3. Character padding (left-aligned, right-aligned, center-aligned)

<span style="color: #800000">&#39;右对齐{:#>10}&#39;.format(10)<br/>&#39;右对齐########10&#39;</span>
Copy after login

4. Use keyword parameters: use key=value to achieve one-to-one assignment replacement

&#39;My name is{name},age:{age}&#39;.format(name=&#39;Anxc&#39;,age=18)
&#39;My name isAnxc,age:18&#39;
Copy after login

5. Precision output of numbers: It feels like the float type output of C language. (Format: {:. #binary

b

##octalHexx
>>> &#39;{:.4f}&#39;.format(1/3)
&#39;0.3333&#39;
>>> &#39;{:4f}&#39;.format(100)
&#39;100.000000&#39;#目前没有发现整数是啥用处
Copy after login
>>> &#39;{:,}&#39;.format(19012390123)
&#39;19,012,390,123&#39;
Copy after login
9. Formatting through the properties of objects (I haven’t learned python classes yet, so there are no examples)

The above is the detailed content of Detailed introduction to format() format output in Python (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
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
o

decimal

7. Thousandth division of numbers

&#39;18的二进制:{:b}&#39;.format(18)
&#39;18的二进制:10010&#39;
>>> &#39;18的八进制:{:o}&#39;.format(18)
&#39;18的八进制:22&#39;
>>> &#39;18的十六进制:{:x}&#39;.format(18)
&#39;18的十六进制:12&#39;
Copy after login

8. Formatting through subscripts