search
HomeBackend DevelopmentPython TutorialPython Full Stack Road Series String Formatting

This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator.

String formats currently provided by Python There are two ways to format:

  • Percent mode

  • format mode

These two This method is applicable to both Python2 and Python3. The percent sign method has always been built-in in Python, and the format method has only come out recently.

Old style % formatting

  • Parameter format

%[(name)][flags][width].[precision]typecode
  • [(name) ]

Optional, used to select the specified key

  • [flags]

Optional, available values ​​are:

Value Description
+ right-aligned; positive numbers are preceded by exactly, negative numbers are preceded by a minus sign
- left Alignment; no sign before positive numbers, plus a minus sign before negative numbers
space Right alignment; add a space before positive numbers, plus a minus sign before negative numbers
0 Right-justified; no sign before positive numbers, and a minus sign before negative numbers; fill the blanks with 0
  • ##[width]

Optional, occupies width

  • .[precision ]

Optional, the number of digits to retain after the decimal point

  • typecode

Required, the parameters are as follows:

ValueDescriptionsGet the return value of the __str__ method of the incoming object and format it to the specified locationr Get the return value of the __repr__ method of the incoming object and format it to the specified locationcInteger: Convert the number to its unicode corresponding value , the decimal range is 0 oConvert the integer to octal representation and format it to the specified location xConvert the integer to hexadecimal representation and format it Format to the specified locationdConvert integers and floating point numbers into decimal representation and format them to the specified locationeConvert integers and floating point numbers into scientific notation and format them to the specified position (lowercase e) E Convert integers and floating-point numbers into scientific notation and format them to the specified position (capital E) fConvert integers and floating-point numbers into floating-point numbers Represent and format it to the specified position (default to 6 decimal places)##FgG%


注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

格式化实例

  • 常用字符串格式化方式

 # %s 代表字符串
 >>> string = "My name is: %s" % ("ansheng")
 >>> string
'My name is: ansheng'
  • 字符串中出现%号的次数要与%之后所提供的数据项个数相同,如果需要插入多个数据,则需要将他们封装进一个元组。

 # %s是姓名,%d是年龄,必须是一个整数,不然会报错
 >>> string = "My name is: %s, I am %d years old" % ("anshen", 20)
 >>> string
'My name is: anshen, I am 20 years old'
  • 给参数起一个名字,后面传值的时候必须是一个字典

 # %(name)s是姓名,%(age)d是年龄,必须是一个整数,传入的值是一个字典格式
 >>> string = "My name is: %(name)s, I am %(age)d years old" % {"name":"anshen", "age":20}
 >>> string
'My name is: anshen, I am 20 years old'
  • 去浮点数后面的位数

 # %.2f小数后面只取两位
 >>> string = "percent %.2f" % 99.97623
 >>> string
'percent 99.98'
  • 给浮点数起一个名字(key)

 >>> string = "percent %(pp).2f" % {"pp":99.97623}
 >>> string
'percent 99.98'
  • 两个百分号代表一个百分号

 >>> string = "percent %(pp).2f%%" % {"pp":99.97623}
 >>> string
'percent 99.98%'

使用{}和format的新格式化

[[fill]align][sign][#][0][width][,][.precision][type]
  • [fill]

可选,空白处填充的字符

  • align

可选,对齐方式(需配合width使用)

Same as above
Automatic adjustment converts integers and floating-point numbers into floating-point or scientific notation (more than 6 digits use scientific notation), and formats them to the specified position (if it is scientific notation, it is e; )
Auto-adjustment converts integers and floating-point numbers into floating-point or scientific notation (use scientific notation for more than 6 digits), and converts them Format to the specified position (E if it is scientific notation;)
When there is a formatting flag in the string, you need to use %% to represent one Percent sign
参数 说明
强制内容左对齐
> 强制内容右对齐(默认)
强制内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
^ 强制内容居中
  • [sign]

可选,有无符号数字

参数 说明
+ 正号加正,负号加负
- 正号不变,负号加负
space 正号空格,负号加负
  • [#]

可选,对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示

  • [,]

可选,为数字添加分隔符,如:1,000,000

  • [width]

可选,格式化位所占宽度

  • [.precision]

可选,小数位保留精度

  • [type]

可选,格式化类型

  • 传入” 字符串类型 “的参数

参数 说明
s 格式化字符串类型数据
空白 未指定类型,则默认是None,同s
  • 传入“ 整数类型 ”的参数

参数 说明
b 将10进制整数自动转换成2进制表示然后格式化
c 将10进制整数自动转换为其对应的unicode字符
d 十进制整数
o 将10进制整数自动转换成8进制表示然后格式化;
x 将10进制整数自动转换成16进制表示然后格式化(小写x)
X 将10进制整数自动转换成16进制表示然后格式化(大写X)
  • 传入“ 浮点型或小数类型 ”的参数

参数 说明
e 转换为科学计数法(小写e)表示,然后格式化;
E 转换为科学计数法(大写E)表示,然后格式化;
f 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
F 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
g 自动在e和f中切换
G 自动在E和F中切换
% 显示百分比(默认显示小数点后6位)

format格式化实例

  • 第一种基本format格式化方式

 >>> string = "My name is: {}, I am {} years old, {} Engineer".format("ansheng",20,"Python")
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 第二种基本format格式化方式

 >>> string = "My name is: {}, I am {} years old, {} Engineer".format(*["ansheng",20,"Python"])
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 给传入的参数加一个索引

 >>> string = "My name is: {0}, I am {1} years old, {0} Engineer".format(*["ansheng",20,"Python"])
 >>> string
'My name is: ansheng, I am 20 years old, ansheng Engineer'
  • 给参数起一个名字(key)

>>> string = "My name is: {name}, I am {age} years old, {job} Engineer".format(name="ansheng",age=20,job="Python")
>>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 字典的方式

 >>> string = "My name is: {name}, I am {age} years old, {job} Engineer".format(**{"name":"ansheng","age":20,"job":"Python"})
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 索引内的索引

 >>> string = "My name is: {0[0]}, I am {0[1]} years old, {0[2]} Engineer".format(["Ansheng",20,"Python"],["An",11,"IT"])
 >>> string
'My name is: Ansheng, I am 20 years old, Python Engineer'
  • 制定参数类型

 >>> string = "My name is: {:s}, I am {:d} years old, {:f} wage".format("Ansheng",20,66666.55)
 >>> string
'My name is: Ansheng, I am 20 years old, 66666.550000 wage'
  • 制定名称(key)的值类型

 >>> string = "My name is: {name:s}, I am {age:d} years old".format(name="Ansheng",age=20)
 >>> string
'My name is: Ansheng, I am 20 years old'
  • 异类实例

 >>> string = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 >>> string
'numbers: 1111,17,15,f,F, 1587.623000%'
  • 索引

 >>> string = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 >>> string
'numbers: 1111,17,15,f,F, 1500.000000%'

原文链接

This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator.

Python目前提供的字符串格式化方式有两种:

  • 百分号方式

  • format方式

这两种方式在Python2Python3中都适用,百分号方式是Python一直内置存在的,format方式为近期才出来的。

旧式%格式化

  • 参数格式

%[(name)][flags][width].[precision]typecode
  • [(name)]

可选,用于选择指定的key

  • [flags]

可选,可供选择的值有:

说明
+ 右对齐;正数前加正好,负数前加负号
- 左对齐;正数前无符号,负数前加负号
space 右对齐;正数前加空格,负数前加负号
0 右对齐;正数前无符号,负数前加负号;用0填充空白处
  • [width]

可选,占有宽度

  • .[precision]

可选,小数点后保留的位数

  • typecode

必选,参数如下:

说明
s 获取传入对象的__str__方法的返回值,并将其格式化到指定位置
r 获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
c 整数:将数字转换成其unicode对应的值,10进制范围为 0
o 将整数转换成 八  进制表示,并将其格式化到指定位置
x 将整数转换成十六进制表示,并将其格式化到指定位置
d 将整数、浮点数转换成十进制表示,并将其格式化到指定位置
e 将整数、浮点数转换成科学计数法,并将其格式化到指定位置(小写e)
E 将整数、浮点数转换成科学计数法,并将其格式化到指定位置(大写E)
f 将整数、浮点数转换成浮点数表示,并将其格式化到指定位置(默认保留小数点后6位)
F 同上
g 自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是e;)
G 自动调整将整数、浮点数转换成 浮点型或科学计数法表示(超过6位数用科学计数法),并将其格式化到指定位置(如果是科学计数则是E;)
% 当字符串中存在格式化标志时,需要用 %%表示一个百分号


注:Python中百分号格式化是不存在自动将整数转换成二进制表示的方式

格式化实例

  • 常用字符串格式化方式

 # %s 代表字符串
 >>> string = "My name is: %s" % ("ansheng")
 >>> string
'My name is: ansheng'
  • 字符串中出现%号的次数要与%之后所提供的数据项个数相同,如果需要插入多个数据,则需要将他们封装进一个元组。

 # %s是姓名,%d是年龄,必须是一个整数,不然会报错
 >>> string = "My name is: %s, I am %d years old" % ("anshen", 20)
 >>> string
'My name is: anshen, I am 20 years old'
  • 给参数起一个名字,后面传值的时候必须是一个字典

 # %(name)s是姓名,%(age)d是年龄,必须是一个整数,传入的值是一个字典格式
 >>> string = "My name is: %(name)s, I am %(age)d years old" % {"name":"anshen", "age":20}
 >>> string
'My name is: anshen, I am 20 years old'
  • 去浮点数后面的位数

 # %.2f小数后面只取两位
 >>> string = "percent %.2f" % 99.97623
 >>> string
'percent 99.98'
  • 给浮点数起一个名字(key)

 >>> string = "percent %(pp).2f" % {"pp":99.97623}
 >>> string
'percent 99.98'
  • 两个百分号代表一个百分号

 >>> string = "percent %(pp).2f%%" % {"pp":99.97623}
 >>> string
'percent 99.98%'

使用{}和format的新格式化

[[fill]align][sign][#][0][width][,][.precision][type]
  • [fill]

可选,空白处填充的字符

  • align

可选,对齐方式(需配合width使用)

参数 说明
强制内容左对齐
> 强制内容右对齐(默认)
强制内容右对齐,将符号放置在填充字符的左侧,且只对数字类型有效。 即使:符号+填充物+数字
^ 强制内容居中
  • [sign]

可选,有无符号数字

参数 说明
+ 正号加正,负号加负
- 正号不变,负号加负
space 正号空格,负号加负
  • [#]

可选,对于二进制、八进制、十六进制,如果加上#,会显示 0b/0o/0x,否则不显示

  • [,]

可选,为数字添加分隔符,如:1,000,000

  • [width]

可选,格式化位所占宽度

  • [.precision]

可选,小数位保留精度

  • [type]

可选,格式化类型

  • 传入” 字符串类型 “的参数

参数 说明
s 格式化字符串类型数据
空白 未指定类型,则默认是None,同s
  • 传入“ 整数类型 ”的参数

参数 说明
b 将10进制整数自动转换成2进制表示然后格式化
c 将10进制整数自动转换为其对应的unicode字符
d 十进制整数
o 将10进制整数自动转换成8进制表示然后格式化;
x 将10进制整数自动转换成16进制表示然后格式化(小写x)
X 将10进制整数自动转换成16进制表示然后格式化(大写X)
  • 传入“ 浮点型或小数类型 ”的参数

参数 说明
e 转换为科学计数法(小写e)表示,然后格式化;
E 转换为科学计数法(大写E)表示,然后格式化;
f 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
F 转换为浮点型(默认小数点后保留6位)表示,然后格式化;
g 自动在e和f中切换
G 自动在E和F中切换
% 显示百分比(默认显示小数点后6位)

format格式化实例

  • 第一种基本format格式化方式

 >>> string = "My name is: {}, I am {} years old, {} Engineer".format("ansheng",20,"Python")
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 第二种基本format格式化方式

 >>> string = "My name is: {}, I am {} years old, {} Engineer".format(*["ansheng",20,"Python"])
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 给传入的参数加一个索引

 >>> string = "My name is: {0}, I am {1} years old, {0} Engineer".format(*["ansheng",20,"Python"])
 >>> string
'My name is: ansheng, I am 20 years old, ansheng Engineer'
  • 给参数起一个名字(key)

>>> string = "My name is: {name}, I am {age} years old, {job} Engineer".format(name="ansheng",age=20,job="Python")
>>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 字典的方式

 >>> string = "My name is: {name}, I am {age} years old, {job} Engineer".format(**{"name":"ansheng","age":20,"job":"Python"})
 >>> string
'My name is: ansheng, I am 20 years old, Python Engineer'
  • 索引内的索引

 >>> string = "My name is: {0[0]}, I am {0[1]} years old, {0[2]} Engineer".format(["Ansheng",20,"Python"],["An",11,"IT"])
 >>> string
'My name is: Ansheng, I am 20 years old, Python Engineer'
  • 制定参数类型

 >>> string = "My name is: {:s}, I am {:d} years old, {:f} wage".format("Ansheng",20,66666.55)
 >>> string
'My name is: Ansheng, I am 20 years old, 66666.550000 wage'
  • 制定名称(key)的值类型

 >>> string = "My name is: {name:s}, I am {age:d} years old".format(name="Ansheng",age=20)
 >>> string
'My name is: Ansheng, I am 20 years old'
  • 异类实例

 >>> string = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 >>> string
'numbers: 1111,17,15,f,F, 1587.623000%'
  • 索引

 >>> string = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 >>> string
'numbers: 1111,17,15,f,F, 1500.000000%'

更多Python全栈之路系列之字符串格式化 相关文章请关注PHP中文网!

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
How to implement factory model in Python?How to implement factory model in Python?May 16, 2025 pm 12:39 PM

Implementing factory pattern in Python can create different types of objects by creating a unified interface. The specific steps are as follows: 1. Define a basic class and multiple inheritance classes, such as Vehicle, Car, Plane and Train. 2. Create a factory class VehicleFactory and use the create_vehicle method to return the corresponding object instance according to the type parameter. 3. Instantiate the object through the factory class, such as my_car=factory.create_vehicle("car","Tesla"). This pattern improves the scalability and maintainability of the code, but it needs to be paid attention to its complexity

What does r mean in python original string prefixWhat does r mean in python original string prefixMay 16, 2025 pm 12:36 PM

In Python, the r or R prefix is ​​used to define the original string, ignoring all escaped characters, and letting the string be interpreted literally. 1) Applicable to deal with regular expressions and file paths to avoid misunderstandings of escape characters. 2) Not applicable to cases where escaped characters need to be preserved, such as line breaks. Careful checking is required when using it to prevent unexpected output.

How to clean up resources using the __del__ method in Python?How to clean up resources using the __del__ method in Python?May 16, 2025 pm 12:33 PM

In Python, the __del__ method is an object's destructor, used to clean up resources. 1) Uncertain execution time: Relying on the garbage collection mechanism. 2) Circular reference: It may cause the call to be unable to be promptly and handled using the weakref module. 3) Exception handling: Exception thrown in __del__ may be ignored and captured using the try-except block. 4) Best practices for resource management: It is recommended to use with statements and context managers to manage resources.

Usage of pop() function in python list pop element removal method detailed explanation of theUsage of pop() function in python list pop element removal method detailed explanation of theMay 16, 2025 pm 12:30 PM

The pop() function is used in Python to remove elements from a list and return a specified position. 1) When the index is not specified, pop() removes and returns the last element of the list by default. 2) When specifying an index, pop() removes and returns the element at the index position. 3) Pay attention to index errors, performance issues, alternative methods and list variability when using it.

How to use Python for image processing?How to use Python for image processing?May 16, 2025 pm 12:27 PM

Python mainly uses two major libraries Pillow and OpenCV for image processing. Pillow is suitable for simple image processing, such as adding watermarks, and the code is simple and easy to use; OpenCV is suitable for complex image processing and computer vision, such as edge detection, with superior performance but attention to memory management is required.

How to implement principal component analysis in Python?How to implement principal component analysis in Python?May 16, 2025 pm 12:24 PM

Implementing PCA in Python can be done by writing code manually or using the scikit-learn library. Manually implementing PCA includes the following steps: 1) centralize the data, 2) calculate the covariance matrix, 3) calculate the eigenvalues ​​and eigenvectors, 4) sort and select principal components, and 5) project the data to the new space. Manual implementation helps to understand the algorithm in depth, but scikit-learn provides more convenient features.

How to calculate logarithm in Python?How to calculate logarithm in Python?May 16, 2025 pm 12:21 PM

Calculating logarithms in Python is a very simple but interesting thing. Let's start with the most basic question: How to calculate logarithm in Python? Basic method of calculating logarithm in Python The math module of Python provides functions for calculating logarithm. Let's take a simple example: importmath# calculates the natural logarithm (base is e) x=10natural_log=math.log(x)print(f"natural log({x})={natural_log}")# calculates the logarithm with base 10 log_base_10=math.log10(x)pri

How to implement linear regression in Python?How to implement linear regression in Python?May 16, 2025 pm 12:18 PM

To implement linear regression in Python, we can start from multiple perspectives. This is not just a simple function call, but involves a comprehensive application of statistics, mathematical optimization and machine learning. Let's dive into this process in depth. The most common way to implement linear regression in Python is to use the scikit-learn library, which provides easy and efficient tools. However, if we want to have a deeper understanding of the principles and implementation details of linear regression, we can also write our own linear regression algorithm from scratch. The linear regression implementation of scikit-learn uses scikit-learn to encapsulate the implementation of linear regression, allowing us to easily model and predict. Here is a use sc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.