Python - 在字符串中搜索和替换元音

时间:2014-11-19 18:03:50

标签: python

我需要在Python中编写代码,以便能够检测字符串中是否存在某个字符并将其替换为我选择的其他字符。例如,我需要用“$& @”替换字符串中的所有元音,所以在字符串“hello world”通过代码之后,它将变成“h $& @ ll $& @ w $ &安培; @rld”。有没有人知道如何使用非常基本的python而不是任何预先存在的函数? 谢谢

4 个答案:

答案 0 :(得分:1)

使用re模块:

import re
string = "Hello world"
print(re.sub("a|e|i|o|u", "xx", string))

这将打印

>>> Hxxllxx wxxrld

答案 1 :(得分:1)

第一种方法

>>> "".join(map(lambda x: '$&@' if x in "aeiou" else x, "hello world"))
'h$&@ll$&@ w$&@rld'

第二种方法

>>> s = "hello world"
>>> for ch in s:
...     if ch in "aeiou":
...             s = s.replace(ch,'$&@')
... 
>>> s
'h$&@ll$&@ w$&@rld

答案 2 :(得分:1)

不使用restr.replace

 def trans(s):
    rpl = "$&@"
    res = ""
    for letter in s: # loop over the string s 
        if letter in {"a","e","i","o","u","A","E","I","O","U"}: # if any letter in vowels
            res+= rpl # add replacement substring
        else:
            res+= letter # else just add the letter
    return  res

要输出单词,我们可以删除连接:

import sys
def trans(s,rpl):
    for letter in s: # loop over the string s
        if letter in {"a","e","i","o","u","A","E","I","O","U"}: # if any letter in vowels
           sys.stdout.write(rpl)
        else:
            sys.stdout.write(letter)
(trans("hello world","$&@"))

答案 3 :(得分:0)

通过re.sub

>>> import re
>>> re.sub(r'[aeiou]', r'$&@', "hello world")
'h$&@ll$&@ w$&@rld'