简体   繁体   English

删除字符串中的字符,而无需多次调用str.replace

[英]Remove characters in a string without multiple calls to str.replace

I'm doing this project for my class and I was just wondering if would it be possible if I could replace a list of vowels, Uppercase and Lowercase in just one line instead of how I have it. 我正在为我的班级做这个项目,我只是想知道是否可以只用一行替换元音,大写和小写的列表,而不用我的方式。 This is in Python. 这是在Python中。

I would like it to be a bit more simple then writing this out completely 我希望它要简单一些然后再完整地写出来

Thanks 谢谢

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)

You can use str.translate and a dict comprehension : 您可以使用str.translatedict理解

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

The dict comprehension is used to create a mapping for str.translate of what characters should be translated into what. dict理解用于创建str.translate的映射, str.translate将哪些字符转换为哪些字符。 Mapping characters to None causes the method to remove them. 将字符映射为“ None会使该方法将其删除。

Note that you could also use str.maketrans instead of the dict comprehension: 请注意,您也可以使用str.maketrans而不是dict理解:

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

you can use re module 你可以使用re模块

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

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

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