杰瑞科技汇

Python字符串替换函数有哪些?

总结速览

函数/方法 描述 是否改变原字符串 适用场景
str.replace() 最常用的方法,用于替换所有或指定次数的子串。 (字符串不可变) 简单、直接的子串替换。
re.sub() 使用正则表达式进行强大而灵活的模式匹配和替换。 需要匹配复杂模式(如通配符、数量词等)。
str.translate() 基于字符映射表进行快速的单字符替换/删除。 需要一次性替换多个不同的单字符,性能要求高。
f-string / format() 主要用于格式化,但也可以通过条件判断实现“替换”效果。 基于条件的内容替换或格式化输出。

str.replace() - 最常用的方法

这是最基本、最直接的字符串替换方法,它可以在一个字符串中查找指定的子串,并将其替换为另一个子串。

Python字符串替换函数有哪些?-图1
(图片来源网络,侵删)

语法

str.replace(old, new[, count])
  • old: 要被替换的旧子串。
  • new: 用于替换的新子串。
  • count (可选): 最多替换的次数,如果省略,则替换所有匹配项。

示例

示例 1: 基本替换

text = "Hello, world! Welcome to the world of Python."
new_text = text.replace("world", "Python")
print(new_text)
# 输出: Hello, Python! Welcome to the Python of Python.

示例 2: 限制替换次数

text = "apple apple apple apple"
# 只替换前两个 "apple"
new_text = text.replace("apple", "orange", 2)
print(new_text)
# 输出: orange orange apple apple

示例 3: 替换不存在的子串 old 子串不存在,replace() 方法会原样返回字符串,不会报错。

text = "This is a test."
new_text = text.replace("python", "java")
print(new_text)
# 输出: This is a test.

re.sub() - 正则表达式替换

当你的替换需求更复杂时,比如要替换匹配某个模式(而不是固定字符串)的内容,就需要使用正则表达式模块 re 中的 sub() 函数。

Python字符串替换函数有哪些?-图2
(图片来源网络,侵删)

语法

re.sub(pattern, repl, string, count=0, flags=0)
  • pattern: 一个正则表达式模式,用来匹配要替换的子串。
  • repl: 用于替换的字符串,也可以是一个函数,该函数的返回值将作为替换内容。
  • string: 原始字符串。
  • count (可选): 最多替换的次数,默认为0,表示替换所有。

示例

示例 1: 替换所有数字

import re
text = "My phone number is 123-456-7890, and my ID is 98765."
# 使用正则表达式 \d 匹配任意数字
new_text = re.sub(r'\d', 'X', text)
print(new_text)
# 输出: My phone number is XXX-XXX-XXXX, and my ID is XXXXX.

示例 2: 使用回调函数进行动态替换 这是 re.sub 最强大的功能之一,你想把所有找到的数字都增加1。

import re
text = "I have 2 apples and 3 oranges."
def increment(match):
    # match.group(0) 是匹配到的字符串
    return str(int(match.group(0)) + 1)
# 匹配一个或多个数字 \d+
new_text = re.sub(r'\d+', increment, text)
print(new_text)
# 输出: I have 3 apples and 4 oranges.

示例 3: 删除标点符号 通过将 repl 设置为空字符串 ,可以实现删除操作。

import re
text = "Hello, world! This is a test."
# 匹配所有非字母数字的字符
new_text = re.sub(r'[^\w\s]', '', text)
print(new_text)
# 输出: Hello world This is a test

str.translate() - 高性能字符映射

str.translate() 是一个专门为高效替换或删除单个字符而设计的函数,它比循环调用 replace() 要快得多,尤其是在处理大量文本时。

Python字符串替换函数有哪些?-图3
(图片来源网络,侵删)

使用它需要两个步骤:

  1. 创建一个转换表(translation table),通常使用 str.maketrans() 方法。
  2. 调用字符串的 translate() 方法并传入该表。

语法

# 1. 创建转换表
table = str.maketrans(x[, y[, z]])
# 2. 应用转换
str.translate(table)
  • str.maketrans():
    • x: 可以是一个字典,键是 Unicode 码位(整数)或字符,值是要替换成的字符或 None(表示删除)。
    • x, y: 两个等长的字符串,第一个字符串中的每个字符将被第二个字符串中对应位置的字符替换。
    • z: 一个字符串,其中的所有字符都将被删除。

示例

示例 1: 字符到字符的替换

text = "This is a test string."
# 创建映射表: 'i' -> 'x', 's' -> '$'
table = str.maketrans('is', 'x$')
new_text = text.translate(table)
print(new_text)
# 输出: Th$x $x a te$t $trtng.

示例 2: 字典映射和删除字符

text = "Hello, 123 World!"
# 创建映射表:
# - 'H' -> 'J'
# - 'e' -> 'a'
# - 'l' -> '1' (重复字符会被最后一个覆盖)
# - 'o' -> None (删除)
# - '1', '2', '3' -> None (删除)
table = str.maketrans({
    'H': 'J',
    'e': 'a',
    'l': '1',
    'o': None,
    '1': None,
    '2': None,
    '3': None
})
new_text = text.translate(table)
print(new_text)
# 输出: Ja1, Wrld!

f-string / str.format() - 条件性替换

虽然这两个方法主要用于格式化,但结合条件表达式(三元运算符),可以实现一种“有则替换,无则保留”的逻辑。

示例

假设我们想把字符串中的 "error" 替换为 "warning",但前提是 "error" 存在。

text = "This is an error message."
keyword = "error"
# 使用 f-string
new_text_f = f"{text.replace(keyword, 'warning') if keyword in text else text}"
print(f"f-string result: {new_text_f}")
# 输出: f-string result: This is a warning message.
# 使用 format()
new_text_format = "{text}".format(text=text.replace(keyword, 'warning') if keyword in text else text)
print(f"format result: {new_text_format}")
# 输出: format result: This is a warning message.

keyword 不存在:

text = "This is a normal message."
keyword = "error"
new_text_f = f"{text.replace(keyword, 'warning') if keyword in text else text}"
print(f"f-string result: {new_text_f}")
# 输出: f-string result: This is a normal message.

如何选择?(决策指南)

  1. 简单替换固定字符串?

    • 首选 str.replace(),简单、直观、易读。
  2. 需要匹配复杂的模式(如数字、邮箱、特定格式的文本)?

    • 必须使用 re.sub(),正则表达式是处理这类问题的标准工具。
  3. 需要替换或删除多个不同的单字符,并且对性能要求很高?

    • 使用 str.translate(),为这种特定场景做了优化,速度最快。
  4. 需要根据某个条件来决定是否替换?

    • 可以结合 f-stringformat() 的条件表达式来实现,代码会比较优雅,或者直接用 if 判断后调用 replace()
分享:
扫描分享到社交APP
上一篇
下一篇