【问题标题】:How to replace multiple characters with different input on same string python如何在同一字符串python上用不同的输入替换多个字符
【发布时间】:2025-12-22 23:10:17
【问题描述】:

我正在尝试替换字符串中的多个字母,我希望用用户输入替换元音,并且我当前的代码用相同的字母替换所有元音,但是我想用不同的用户输入替换元音.下面是我想要的示例,以及下面的代码。

我想要什么

input1 = zz
input2 = xx
input3 = yolo

output = yzzlxx

我有什么

input1 = zz
input2 = xx
input3 = yolo

output = yzzlzz

这是我的代码。

def vwl():
    syl1 = input("Enter your first syllable: ")
    syl2 = input("Enter the second syllable: ")
    translate = input("Enter word to replace vowels in: ")

    for ch in ['a','e','i','o','u']:
        if ch in translate:
            translate=translate.replace(ch,syl1,)

    for ch in ['a','e','i','o','u']:
        if syl1 in translate:
            translate=translate.replace(ch,syl2,)

    print (translate)

【问题讨论】:

  • Ryan:这是你在做的家庭作业吗?如果是这样,请使用“作业”标签。
  • @MarkHildreth:实际上,homework 标签最近已被弃用。见here
  • @DSM:感谢您的来信。我的错。
  • 什么决定了哪些输入替换了哪些元音?

标签: python string replace


【解决方案1】:

方法replace 需要一个额外的参数count

translate=translate.replace(ch,syl1,1)
break # finish the for loop for syl1

将仅替换 ch 的第一个实例,而 break 将确保您不会将任何后续元音替换为 syl1

同样:

translate=translate.replace(ch,syl2,1)
break # finish the for loop

【讨论】:

  • 如果用户输入yoli(他仍然会得到yxxlxx),这将无济于事。
  • 这个要求有点奇怪......(在str.replace 上使用count 也是我的第一直觉)
  • 是的,我认为可以。 (很高兴您没有删除您的答案。我喜欢尽可能避免使用re)(+1)。
【解决方案2】:

你可以使用正则表达式:

translate = re.sub('a|e|i|o|u',input1,translate,count=1)
translate = re.sub('a|e|i|o|u',input2,translate,count=1)

例子:

>>> input1 = 'zz'
>>> input2 = 'xx'
>>> translate = 'yolo'
>>> import re
>>> translate = re.sub('a|e|i|o|u',input1,translate,count=1)
>>> translate
'yzzlo'
>>> translate = re.sub('a|e|i|o|u',input2,translate,count=1)
>>> translate
'yzzlxx'

【讨论】: