首页 > 解决方案 > 在python中返回没有元音的字符串

问题描述

我想取一个字符串并将其打印回来,不带 Ex: for 的元音:for 'the quick brown fox jumps over the lazy dog', I want to get 'th qck brwn fx jmps vr th lzy dg'

我曾尝试使用列表理解,但我只能将句子拆分为单词列表,我无法进一步将单词拆分为单个字母以删除元音。这是我尝试过的:

a = 'the quick brown fox jumps over the lazy dog'
b = a.split()
c = b.split()
d = [x for x in c if (x!="a" or x!="e" or x!= "e" or x!="i" or x!="u")]
e = ' '.join(d)
f = ' '.join(f)
print(f)

标签: pythonstringlist

解决方案


您不需要拆分原始字符串,因为在 Python 中循环遍历字符串会遍历字符串的字符。

使用列表推导,您只需检查当前字符char是否为元音并在这种情况下排除它。

然后,最后,您可以再次连接字符串。

a = 'the quick brown fox jumps over the lazy dog'
s = [char for char in a if char not in ('a', 'e', 'i', 'o', 'u')]
print(''.join(s))
# th qck brwn fx jmps vr th lzy dg

如果您的句子可能包含大写元音,并希望过滤掉它们,您可以使用str.lower()

s = [char for char in a if char.lower() not in ('a', 'e', 'i', 'o', 'u')]

推荐阅读