Python: Is there a way to remove a character without regard to capitalization?

41 Views Asked by At

My code is supposed to remove vowels from the user inputted string. It works correctly, but I'm trying to see if there is a way to simplify my code. A screenshot of my code

I originally didn't have the line:

     elif i == "A" or i == "E" or i == "I" or i == "O" or i == "U":
        n.replace(i, "")
        output = output

but I added it because when my input contained capitalized vowels it would not remove the vowels because they were capitalized.

Is there a way to rewrite my code so I can remove the vowels that are both lowercase and capitalized without the extra lines?

3

There are 3 best solutions below

2
Builderboy271 On

(edited to fix)

Here is one way to do it:

word = input()

output = ""
for letter in word:
    if letter.casefold() not in "aeiou":
        output += letter

print(output)

to make it into a function:

def remove_vowels(word):
    output = ""
    for letter in word:
        if letter.casefold() not in "aeiou":
            output += letter
    return output
0
Bohdan On

You can check in lowercase, this way you do not duplicate comparisons:

if i.lower() in 'aeiou':
    n.replace(i, "")

but you can write even simpler code with no loops using regular expression:

import re

def remove_vowels(n):
    return re.sub(r'[aueoi]', '', n, flags=re.IGNORECASE)

It basically removes any char from the list [a, u, e, o, i], adding flags=re.IGNORECASE matches both lower and upper case letters, and replaces each letter with '' basicaly removing it

0
import random On

You could use the regular expressions, in particular the built-in re.sub function:

import re
text = "ThE quick brown fOx jumps over the lazy dog"
re.sub("[aeiou]","", text, flags=re.IGNORECASE)

'Th qck brwn fx jmps vr th lzy dg'

The regular expression [aeiou] will match any vowel and then the flag re.IGNORECASE will allow the expression to match the upper case vowels as well. You could instead extend the pattern to [AEIOUaeiou].