一次替换字符串中的多个字符

新手上路,请多包涵

我想用空格替换字符串中的所有元音:

 string = str(input('Enter something to change'))
replacing_words = 'aeiou'

for i in replacing_words:
    s = string.replace('replacing_words', ' ')

print(s)

如果这是一个错误的代码,有人可以协助提供正确的代码和解释,为什么它不起作用?

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

阅读 392
2 个回答
  • 您在 for 循环中使用文字 ‘replacing_words’ 而不是变量 i 。
  • 您不替换原始字符串以再次修改它,而是创建一个新字符串,导致仅显示最后一个替换

这将是正确的代码。

 string = input('Enter something to change')
vowels = 'aeiouy'

for i in vowels:
    string = string.replace(i, ' ')

print(string)

另外,我认为输入返回一个字符串“类型”。所以调用 str 不会有任何效果。不确定。另外 #2:y 也是元音(如果您想彻底了解的话,åäö 和其他变音符号和奇怪的字符也是元音)。

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

您可以定义一个 转换表。这是一个 Python2 代码:

 >>> import string
>>> vowels = 'aeiou'
>>> remove_vowels = string.maketrans(vowels, ' ' * len(vowels))
>>> 'test translation'.translate(remove_vowels)
't st tr nsl t  n'

它快速、简洁并且不需要任何循环。

对于 Python3,你会写:

 'test translation'.translate({ord(ch):' ' for ch in 'aeiou'}) # Thanks @JonClements.

原文由 Eric Duminil 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题