简体   繁体   中英

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' .

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.

Using a list comprehension , you just check if the current character char is a vowel and exclude it in such a case.

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() :

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

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

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 :

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM