[英]Return string without vowels in python
I want to take a string and print it back without the vowels for Ex: for 'the quick brown fox jumps over the lazy dog'
, I want to get 'th qck brwn fx jmps vr th lzy dg'
.我想取一个字符串并将其打印回来,不包含 Ex: 的元音:对于'the quick brown fox jumps over the lazy dog'
,我想得到'th qck brwn fx jmps vr th lzy dg'
。
I have tried using list comprehension, but I am only able to split the sentence into a list of words, I can't further split the words into individual letters in order to remove the vowels.我曾尝试使用列表理解,但我只能将句子拆分为单词列表,我无法进一步将单词拆分为单个字母以删除元音。 Here's what I've tried:这是我尝试过的:
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)
You won't need to split the original string, since looping through a string in Python iterates through the characters of the string.您不需要拆分原始字符串,因为在 Python 中循环遍历字符串的字符。
Using a list comprehension , you just check if the current character char
is a vowel and exclude it in such a case.使用列表推导,您只需检查当前字符char
是否为元音并在这种情况下排除它。
Then, at the end, you can join up the string again.然后,最后,您可以再次连接字符串。
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
If your sentence may contain uppercase vowels, and wish to filter those out as well, you can do so using str.lower()
:如果您的句子可能包含大写元音,并希望过滤掉它们,您可以使用str.lower()
来实现:
s = [char for char in a if char.lower() not in ('a', 'e', 'i', 'o', 'u')]
You can follow costaparas answer or also use regexes to remove vowels您可以按照costaparas 的回答,也可以使用正则表达式删除元音
import re
se = 'the quick brown fox jumps over the lazy dog'
se = re.sub(r"[aeiouAEIOU]", '', se)
re.sub
replaces all occurence of the regex with second string re.sub
用第二个字符串替换所有出现的正则表达式
Please do this you will get your answer:-请这样做你会得到你的答案:-
vowels = ('a', 'e', 'i', 'o', 'u')
for x in string.lower():
if x in vowels:
string = string.replace(x, "")
# Print string without vowels
print(string)
your_string = "the quick brown fox jumps over the lazy dog"
vowel_remove(your_string) ```
I tried and get a result which you can see in given image:-
`developer@developer-x550la:~/MY_PROJECT/Extract-Table-Pdf/extractPdf$ python3 stak.py
th qck brwn fx jmps vr th lzy dg
`
Simple one-liner with filter
:带filter
的简单单线:
>>> s = 'the quick brown fox jumps over the lazy dog'
>>> ''.join(filter(lambda x: x not in 'AEIOUaeiou', s))
'th qck brwn fx jmps vr th lzy dg'
vowels = ['a','e','i','o','u', 'A', 'E', 'I', 'O', 'U']
se = 'the quick brown fox jumps over the lazy dog'
for vowel in vowels:
se = se.replace(vowel,'')
With the replace()
method使用replace()
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.