如何仅替换字符串中的第二个字符实例?

时间:2020-12-22 18:43:42

标签: python replace case

我正在尝试按照以下规则仅替换字母的第二个实例:

a becomes 4
e becomes 3
i becomes !
o becomes ooo
u becomes |_|

到目前为止,我已经设法做到了,但是为了实现这一点,我不得不将所有字符更改为小写。

因此,"Hello World" 将是 "hello wooorld"

有没有办法在不改变大小写的情况下替换字符串中字符的第二个实例?

def vowel_swapper(string):
    # ==============
    # Your code hered
    return string.lower().replace("a", "4",2).replace("4","a",1).replace("e", "3",2).replace("3","e",1).replace("i", "!",2).replace("!", "i",1).replace("o", "ooo", 2).replace("ooo","o",1).replace("u", "|_|",2).replace("|_|","u",1)
    # ==============


print(vowel_swapper("aAa eEe iIi oOo uUu")) # Should print "a4a e3e i!i o000o u|_|u" to the console
print(vowel_swapper("Hello World")) # Should print "Hello Wooorld" to the console 
print(vowel_swapper("Everything's Available")) # Should print "Ev3rything's Av4!lable" to the console

0 个答案:

没有答案