python - 在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)
解决方案
您不需要拆分原始字符串,因为在 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')]
推荐阅读
- sql - Oracle中基于条件的字符串替换
- maven - 尝试将 Jersey-core 1.X 迁移到 Jersey 2.x Glassfish Maven
- python - PATH="/custom/dir:$PATH" 前置而不是附加 - Conda vs Pyenv
- yaml - 单转义的yaml输出?
- javascript - 在 vue.js 中访问 javascript 对象
- c++ - 如何解决此重载错误 (c1) 情况?
- geopandas - 上下文制作奇怪的背景图
- linux - 如何阻止 kuberenetes pod 内的 postgres 进程响应
- django - 使用 as_crispy_form 模板标签更改 help_text 位置
- json - 前端/后端之间的新 Date() 时间戳差异