Python字符串替换的完整指南

888 阅读2分钟

Python String Substitution Example

Python 内置的字符串类支持序列类型方法。对于正则表达式,见re 模块中基于正则表达式的字符串函数。

Python 字符串替换

要在Python替换 字符串,可以使用**replace()**方法。 字符串 replace() 是一个内置的 Python 函数,用于用另一个子串替换一个子串。

语法

string.replace(old, new, count)

参数

  1. old-这是你要替换的一个旧的子串。
  2. new-这是一个新的子串,它将取代旧的子串。
  3. count参数count是你想用新子串替换旧子串的次数。

返回值

replace()函数返回一个字符串的副本,其中所有出现的子串都被另一个子串所替换。

例子

让我们创建一个字符串,用San 子串代替san

string = "san francisco san diego san antonio san jose"

# Subsitute san with San at all occurances
print(string.replace("san", "San"))

# Substitute san with San at first 2 occurances
print(string.replace("san", "San", 2))

输出

San francisco San diego San antonio San jose
San francisco San diego san antonio san jose

你可以看到,在第一个例子中,replace()函数在字符串中的所有地方都用San替换了San。在第二个例子中,它在前两次出现的地方用San替换了san

Python字符串格式化

在Python中,有三个选项可以用来格式化字符串。

  1. Python2的老式方法,其中**%**运算符替换了字符串。
  2. 使用Python3 format()方法。
  3. Python f-strings。它允许你在你的字符串字面上指定表达式。

替换字符串的%操作符

接受C-printf风格格式字符串的%格式器。请看下面的例子。

# app.py

substitute = "Homer"
print("Yello %s" % substitute)
print("Yello %s %s" % (substitute, 'simpson'))

输出

Yello Homer
Yello Homer simpson

Python format()函数用于替换字符串

Python字符串format()允许多种替换和数值格式化。format()方法通过位置格式化将字符串中的项目连接起来。

# app.py

sub = "Homer"
print("Yello {}".format(sub))

输出

Yello Homer

在这个例子中,format()方法替换了子变量并格式化了字符串。

Python 3.6+ f-strings

要创建一个f-字符串,在字符串前加一个字母**"f"。**F-字符串提供了一种简洁方便的方法,可以将python表达式嵌入到字符串字面中进行格式化。

sub1 = "Yello"
sub2 = "Simpson"
print(f"{sub1} Homer {sub2}")

输出

Yello Homer Simpson

F-字符串比两种最常用的字符串格式化机制要快。

这就是Python字符串置换的内容了。