Python 字符串格式化

简介: Python 字符串格式化


一、引言

在Python编程中,字符串格式化是一个常见的任务,它涉及到将变量、表达式或其他数据嵌入到字符串中的指定位置,以生成具有动态内容的字符串。Python提供了多种字符串格式化的方法,包括旧式的 % 格式化、str.format() 方法以及Python 3.6中引入的f-string(格式化字符串字面量)。本文将详细介绍这些字符串格式化方法,并通过示例代码展示它们的使用。

二、旧式 % 格式化

% 格式化是Python中较早期的字符串格式化方法,它使用 % 运算符将变量或表达式嵌入到字符串中。在字符串中,使用 %s%d%f 等占位符来表示要插入的位置,其中 %s 用于字符串,%d 用于整数,%f 用于浮点数。

示例代码:

name = "Alice" 
age = 30 
salary = 8000.50 
# 使用 %s、%d、%f 占位符进行格式化 
formatted_string = "My name is %s, I am %d years old, and my salary is %.2f." % (name, age, salary) 
print(formatted_string)

输出结果:

My name is Alice, I am 30 years old, and my salary is 8000.50.

注意,在 %f 占位符中,.2f 表示保留两位小数。

三、str.format() 方法

str.format() 方法是Python中更灵活、更强大的字符串格式化方法。它使用大括号 {} 作为占位符,并通过 format() 方法中的参数来填充这些占位符。在占位符内部,可以使用更复杂的表达式和格式化选项。

示例代码:

name = "Bob" 
age = 25 
location = "New York" 
# 使用 str.format() 方法进行格式化 
formatted_string = "My name is {}, I am {} years old, and I live in {}.".format(name, age, location) 
print(formatted_string) 
# 也可以使用关键字参数进行格式化 
formatted_string = "My name is {name}, I am {age} years old, and I live in {location}.".format(name=name, age=age, location=location) 
print(formatted_string) 
# 格式化浮点数并保留两位小数 
salary = 9500.789 
formatted_string = "My salary is {:.2f}.".format(salary) 
print(formatted_string)

输出结果:

My name is Bob, I am 25 years old, and I live in New York. 
My name is Bob, I am 25 years old, and I live in New York. 
My salary is 9500.79.

str.format() 方法中,还可以使用索引、属性访问、字典等方式来提供占位符的值。

四、f-string(格式化字符串字面量)

f-string是Python 3.6及更高版本中引入的一种新的字符串格式化方法。它使用在字符串前加上字母 fF 来标识,并在字符串内部使用大括号 {} 来包裹变量或表达式。f-string在运行时会自动计算大括号内的表达式,并将其结果嵌入到字符串中。

示例代码:

name = "Charlie" 
age = 35 
salary = 10000.0 
# 使用 f-string 进行格式化 
formatted_string = f"My name is {name}, I am {age} years old, and my salary is {salary:.2f}." 
print(formatted_string) 
# 在 f-string 中进行复杂的表达式计算 
formatted_string = f"The sum of 10 and 20 is {10 + 20}." 
print(formatted_string)

输出结果:

My name is Charlie, I am 35 years old, and my salary is 10000.00. 
The sum of 10 and 20 is 30.

f-string的优点是简洁易读,并且支持在字符串内部直接进行复杂的表达式计算。这使得它在许多情况下成为首选的字符串格式化方法。

四、f-string(格式化字符串字面量)的高级用法

f-string不仅提供了基本的变量替换功能,还支持更复杂的表达式和函数调用,这使得它在处理动态字符串时非常强大和灵活。

1. 表达式求值

在f-string中,你可以直接编写Python表达式,并在运行时求值。

x = 10 
y = 20 
formatted_string = f"The result of x * y is {x * y}." 
print(formatted_string)

输出结果:

The result of x * y is 200.

2. 函数调用

你可以在f-string中调用函数,并将其返回值嵌入到字符串中。

def greet(name): 
return f"Hello, {name}!" 
name = "David" 
formatted_string = f"{greet(name)}" 
print(formatted_string)

输出结果:

Hello, David!

3. 格式化选项

f-string还支持与str.format()方法类似的格式化选项,用于控制数字的显示方式。

pi = 3.141592653589793 
formatted_string = f"Pi is approximately {pi:.3f}." 
print(formatted_string)

输出结果:

Pi is approximately 3.142.

4. 嵌套f-string

虽然在实际应用中并不常见,但你可以在f-string中嵌套另一个f-string。

name = "Eve" 
greeting = f"Hello, {name}!" 
formatted_string = f"The greeting is '{greeting}'." 
print(formatted_string)

输出结果:

The greeting is 'Hello, Eve!'.

5. 调试代码

f-string的另一个用途是在调试代码时打印变量的值。由于f-string是即时求值的,所以你可以轻松地将变量的值嵌入到日志或调试信息中。

x = 5 
y = 10 
print(f"x is {x} and y is {y}")

输出结果:

x is 5 and y is 10

五、性能考虑

在大多数情况下,字符串格式化的性能并不是主要的关注点,因为Python字符串操作通常非常快。然而,在处理大量数据或性能敏感的应用程序中,了解不同字符串格式化方法的性能差异可能会有所帮助。

通常来说,f-string在Python 3.6及更高版本中提供了最佳的性能,因为它在编译时就被解析和转换为一个常量字符串,减少了运行时的开销。然而,如果你使用的是Python 3.5或更早版本,那么str.format()方法可能是更好的选择。

六、总结

Python提供了多种字符串格式化方法,每种方法都有其独特的优点和适用场景。%格式化是Python早期的解决方案,虽然功能相对有限但足够简单。str.format()方法提供了更强大和灵活的格式化选项,并支持更复杂的表达式和函数调用。而f-string则是Python 3.6及更高版本中引入的一种新的、简洁易读的字符串格式化方法,它支持在字符串内部直接进行表达式求值和函数调用。在选择使用哪种字符串格式化方法时,你应该根据你的具体需求和Python版本做出决策。

 

目录
相关文章
|
13天前
|
Python
使用Python处理字符串。
使用Python处理字符串。
|
13天前
|
算法框架/工具 索引 Python
Python基础教程(第3版)中文版 第三章 使用字符串(笔记)
Python基础教程(第3版)中文版 第三章 使用字符串(笔记)
|
2天前
|
数据采集 开发者 Python
在Python中判断字符串中是否包含字母
在Python中判断字符串中是否包含字母
15 4
|
1天前
|
Python
python之字符串定义、切片、连接、重复、遍历、字符串方法
python之字符串定义、切片、连接、重复、遍历、字符串方法
4 0
python之字符串定义、切片、连接、重复、遍历、字符串方法
|
7天前
|
Python
Python语言提供了多种输出格式化的方法,这些方法随着时间的推移和版本的更新而发展
【6月更文挑战第19天】Python格式化方法包括过时的`%`操作符,`str.format()`,推荐的f-string(Python 3.6+)和Template strings。f-string提供最佳的可读性和性能,`str.format()`是通用的,而`%`不推荐使用。模板字符串用于特定场景。对于旧版Python,使用`str.format()`或`%`。
16 4
|
7天前
|
IDE 前端开发 开发工具
怎么在isort Python 代码中的导入语句进行排序和格式化
`isort` 是一个Python工具,用于自动排序和格式化代码中的导入语句,提高代码整洁度和可读性。它支持自动排序、保留空白和注释、自定义排序规则、与多种编辑器集成以及命令行使用。安装`isort`可通过`pip install isort`,使用时可直接在Python代码中导入或通过命令行处理文件。示例展示了如何在代码中使用`isort`进行导入排序,包括基本排序、自定义设置和处理多个文件。`isort`适用于标准库、第三方库和自定义模块的导入排序,还可忽略特定导入,并能与IDE和编辑器插件集成,提升开发效率。
|
8天前
|
IDE 开发工具 开发者
isort——Python 代码中的导入语句进行排序和格式化
isort,全称是 "Import Sorting",是一个 Python 工具,用来对 Python 代码中的导入语句进行排序和格式化。它可以帮助我们按照一定的规则对导入的模块进行排序,使得代码更加整洁,易于阅读和维护。
|
11天前
|
Python 索引
【Python字符串攻略】:玩转文字,编织程序的叙事艺术
【Python字符串攻略】:玩转文字,编织程序的叙事艺术
|
11天前
|
IDE 开发工具 Python
black--一键格式化Python代码
black--一键格式化Python代码
|
11天前
|
Python
刷题——Python篇(3)字符串
刷题——Python篇(3)字符串