python中不带元音的返回字符串

2024-03-29 12:30:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一个字符串打印回来,不带Ex的元音:对于'the quick brown fox jumps over the lazy dog',我想得到'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)

Tags: orthe列表quick单词lazyoversplit
3条回答

请这样做,您将得到您的答案:-

    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
`

您可以跟随costaparas answer,也可以使用正则表达式删除元音

import re
se = 'the quick brown fox jumps over the lazy dog'
se = re.sub(r"[aeiouAEIOU]", '', se)

re.sub用第二个字符串替换所有出现的正则表达式

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

使用list comprehension,您只需检查当前字符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

如果您的句子可能包含大写元音,并且希望过滤掉这些元音,您可以使用^{}

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

相关问题 更多 >