如何在Python中删除字符串中的辅音?
这个问题最简单的方法是使用正则表达式。您可以用“|”符号分隔多个字符,并使用re.sub(chars_to_replace,string_to_replace_with,str)。例如:
>>> import re
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> re.sub('|'.join(consonants), "", "Hello people", flags=re.IGNORECASE)
"eo eoe"
注意:您还可以使用[]来创建用于在正则表达式中替换字符的字符组。
如果您想要仅保留元音并删除所有其他字符,可以使用较简单的版本。注意它也将删除空格、数字等。例如,
>>> import re
>>> re.sub('[^aeiou]', "", "Hello people", flags=re.IGNORECASE)
"eoeoe"
您也可以按以下方式过滤掉辅音:
>>> consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
>>> s = "Hello people"
>>> ''.join(c for c in s if c.lower() not in consonants)
'eo eoe'