简体   繁体   English

在 Python 中使用 replace() function 替换字符串中的元音

[英]Using replace() function in Python to replace vowels in a string

I'm trying to create a function that accepts a string and replaces the vowels with other characters.我正在尝试创建一个接受字符串并用其他字符替换元音的 function。

I've written some code, but when I run it in IDLE the output is 'None', but I'm expecting it to be '44 33 !!我已经编写了一些代码,但是当我在 IDLE 中运行它时,output 是“无”,但我希望它是“44 33 !! ooo000 | ooo000 | || || |' |'

I have the below:我有以下内容:

def vowel_swapper(string):
    for char in string:
        if char in 'aeiouAEIOU':
            char.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3')\
            .replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

print(vowel_swapper("aA eE iI oO uU"))

Where have I gone wrong here?我在这里哪里出错了?

Edit: Thanks for all of the responses.编辑:感谢所有回复。 I will also take on the advice about using a dictionary and look into it.我还将接受有关使用字典的建议并进行研究。

In python, .replace is not a in place modification.在 python 中, .replace不是就地修改。 It returns the result of said modification rather than doing an in place modification.返回所述修改的结果,而不是进行就地修改。

For what you want to achieve, you cannot do it while looping through the string and possibly assigning each changed char to the string.对于您想要实现的目标,您不能在遍历字符串并可能将每个更改的char分配给字符串时执行此操作。 Python strings are immutable . Python 字符串是不可变的。

Instead, you should do-相反,你应该这样做——

def vowel_swapper(s: str):
    return s.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3').replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

Which will replace all the characters you want to replace at once and return the result.它将一次替换您替换的所有字符并返回结果。

Output-输出-

44 33 !! ooo000 |_||_|

A more elegant approach however, would be to use a dict .然而,更优雅的方法是使用dict

def vowel_swapper(s: str):
    replacements = {'a': '4', 'A': '4', 'e': '3', 'E': '3', 'i': '!', 'I':  '!', 'o': 'ooo', 'O': '000', 'u': '|_|', 'U': '|_|'}
    return "".join([replacements.get(c, c) for c in s])

Output-输出-

44 33 !! ooo000 |_||_|

Here, we're using .get (with a default value) to efficiently and pythonically, replace and map each character in given string在这里,我们使用.get (带有默认值)来高效和 Python 地替换和 map 给定字符串中的每个字符

You are looping through the string and not updating the value of the characters in the string with the replace method.您正在遍历字符串,而不是使用 replace 方法更新字符串中字符的值。

You can use:您可以使用:

def vowel_swapper(string):
     return string.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3').replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

vowel_swapper("aA eE iI oO uU")

May I suggest a another way to approach the problem that uses dictionary instead of using replace method multiple times?我可以建议另一种方法来解决使用字典而不是多次使用替换方法的问题吗?

string= "aA eE iI oO uU xx"
swap_dic= {'a':'4', 'e':'3','i':'!','o':'000','u':'|_|' }

string= string.lower()

for char in string:
    if char in swap_dic.keys():
        string= string.replace(char,swap_dic[char])
    
print(string)

you don't need to check every character whether they are a vowel or not while using replace , as str.replace return the replace new string with all the replace character with new one您不需要在使用replace时检查每个字符是否为元音,因为str.replace将替换新字符串与所有替换字符返回为新字符

def vowel_swapper(string):

    res = string.replace('a', '4').replace('A', '4').replace('e', '3').replace('E', '3')\
            .replace('i', '!').replace('I', '!').replace('o', 'ooo').replace('O', '000').replace('u', '|_|').replace('U', '|_|')

    return res
print(vowel_swapper("aA eE iI oO uU"))

output output

44 33 !! ooo000 |_||_|

The replace method works on entire strings, and returns a new string. replace方法适用于整个字符串,并返回一个新字符串。

You can save time by converting your string to lowercase, almost halving the methods called.您可以通过将字符串转换为小写来节省时间,几乎将调用的方法减半。

def vowel_swapper(string):
    return string.replace('o', 'ooo').replace('O', '000').lower().replace('a', '4').replace('e', '3').replace('u', '|_|')

As an alternative to doing replace().replace().replace()... you can use str.maketrans() on a dict() of replacement characters then run translate() on the string:作为replace().replace().replace()...您可以在替换字符的dict() str.maketrans()然后在字符串上运行translate()


def vowel_swapper(string):
    table = str.maketrans({'a': '4', 'A': '4',
                           'e': '3', 'E': '3',
                           'i': '!', 'I': '!',
                           'o': 'ooo', 'O': '000',
                           'u': '|_|', 'U': '|_|',
                           }
                          )

    return string.translate(table)


print(vowel_swapper("aA eE iI oO uU"))

Output: Output:

44 33 !! ooo000 |_||_|
def vowel_swapper(stringer):
    new_str = ""
    for char in stringer:
        char = char.replace("A", "4")       # 
These replace the characters
        char = char.replace("E", "3")       # 
Char.replace returns a value rather than resets 
the value of the string it is used on 
        char = char.replace("I", "!")
        char = char.replace("O", "000")
        char = char.replace("U", "|_|")
        char = char.replace("a", "4")
        char = char.replace("e", "3")
        char = char.replace("i", "!")
        char = char.replace("o", "ooo")
        char = char.replace("u", "|_|")

        print(char)
        new_str = new_str + char        # 
creating and building a new string to return 
    return new_str
    
print(vowel_swapper('aA eE iI oO uU'))

when using char.replace() remember it is a method so you get a value out of it.使用 char.replace() 时,请记住它是一种方法,因此您可以从中获得价值。

also your function did not return a value.您的 function 也没有返回值。

:) :)

Use the letters needed to be removed from the string in dict (we can access the dict in O(1) time complexity)dict中使用需要从字符串中删除的字母(我们可以在O(1)时间复杂度中访问 dict)

popouts = {'a': '4', 'A': '4', 'e': '3', 'E': '3', 'i': '!', 'I':  '!', 'o': 'ooo', 'O': '000', 'u': '|_|', 'U': '|_|'}

our input string for example:我们的输入字符串例如:

sst="fpooabraabdbuuososso"
splited_str=(" ".join(sst)).split()


for j in range(len(splited_str)):
  if splited_str[j] in popouts:
    splited_str[j]=(popouts[splited_str[j]])

final_string="".join(splited_str)
def rep_vowels(vs):
    for i in vs:
        if i in "aeiouAEIOU":
            return vs.replace("a", "*").replace("A", "*").replace("e", "*").replace("E", "*").replace("I", "*").replace("i","*").replace("o","*").replace("O", "*").replace("u", "*").replace("U", "*")

print(rep_vowels("COMPUTER"))  

I've replaced it with star(shift+8)我已将其替换为 star(shift+8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM