删除字符串中的字符而不多次调用str.replace

时间:2014-11-03 22:35:25

标签: python string replace

我正在为我的班级做这个项目,我只是想知道如果我能在一行中替换一个元音列表,大写和小写而不是我的方式是否可行。这是在Python中。

我希望它更简单然后完全写出来

由于

s= input ('Enter a Sentence: ')
s = str(s.replace ('a',''))
s = str(s.replace ('e',''))
s = str(s.replace ('i',''))
s = str(s.replace ('o',''))
s = str(s.replace ('u',''))
s = str(s.replace ('A',''))
s = str(s.replace ('E',''))
s = str(s.replace ('I',''))
s = str(s.replace ('O',''))
s = str(s.replace ('U',''))
print (s)

2 个答案:

答案 0 :(得分:2)

您可以使用str.translatedict comprehension

>>> 'aeiouAEIOU'.translate({ord(x):None for x in 'aeiouAEIOU'})
''
>>>

dict理解用于为str.translate创建应该将哪些字符翻译成什么的映射。将字符映射到None会导致该方法将其删除。

请注意,您也可以使用str.maketrans代替dict理解:

>>> 'aeiouAEIOU'.translate(str.maketrans('', '', 'aeiouAEIOU'))
''
>>>

答案 1 :(得分:0)

您可以使用re模块

import re
s= input('Enter a Sentence: ')
re.sub('[AEIOUaeiou]','',s)