如何在 Python 中用字符串替换一组或一组字符

新手上路,请多包涵

我正在尝试制作一个简单的脚本来替换文本中所有出现的特定组或字符集(或字符串集)。

在这种情况下,我将尝试用特定字符串替换所有字母“a、e、i、o、u”。

我的脚本:

 def replace_all(text, repl):
    text1 = text.replace("a", repl)
    text2 = text1.replace("e", repl)
    text3 = text2.replace("i", repl)
    text4 = text3.replace("o", repl)
    text5 = text4.replace("u", repl)
    return text5

有没有更简单的方法呢?如果我需要替换更大的字符或字符串组怎么办?像这样链接它似乎并不是真的有效。

这可能是一个原始问题。但是,我仍处于学习阶段,所以也许我会在以后的课程中得到它。预先感谢您的任何建议。

原文由 Blacho 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 410
2 个回答

我的知识告诉我有 3 不同的方法,所有这些都比你的方法短:

  • 使用 for-loop
  • 使用 generator-comprehension
  • 使用 regular expressions

首先,使用 for-loop 。这可能是对您的代码最直接的改进,本质上只是将 5 行与 .replace 减少到 2

 def replace_all(text, repl):
    for c in "aeiou":
        text = text.replace(c, repl)
    return text


您也可以使用 generator-comprehension 结合 str.join 方法在一行中完成。这会更快(如果这很重要),因为它很复杂 O(n) 因为我们将遍历每个字符并对它进行一次评估 (第一种方法是复杂性 O(n^5) 因为 Python 会通过 text 循环五次以进行不同的替换)

所以,这个方法很简单:

 def replace_all(text, repl):
    return ''.join(repl if c in 'aeiou' else c for c in text)


最后,我们可以使用 re.sub 替换集合中的所有字符: [aeiou] 文本 repl 。这是最短的解决方案,可能也是我推荐的:

 import re
def replace_all(text, repl):
    return re.sub('[aeiou]', repl, text)


正如我在开始时所说,所有这些方法都完成了任务,因此我没有必要提供单独的测试用例,但它们确实如此测试所示工作:

 >>> replace_all('hello world', 'x')
'hxllx wxrld'


更新

我注意到了一种新方法: str.translate

 >>> {c:'x' for c in 'aeiou'}
{'a': 'x', 'e': 'x', 'i': 'x', 'o': 'x', 'u': 'x'}
>>> 'hello world'.translate({ord(c):'x' for c in 'aeiou'})
'hxllx wxrld'

这个方法也是 O(n) ,所以和前两个一样有效。

原文由 Joe Iddon 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是 正则表达式 的好地方:

 import re

def replace_all(text, repl):
    return re.sub('[aeiou]', repl, text)

这将适用于您要替换单个字符的问题中的情况。如果要替换一组较长的字符串:

 def replace_all(text, to_replace, replacement):
    pattern = '|'.join(to_replace)
    return re.sub(pattern, replacement, text)

>>> replace_all('this is a thing', ['thi','a'], 'x')
'xs is x xng'

原文由 Nathan Vērzemnieks 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题