Conor Conor - 9 months ago 64
Python Question

How to get vowels, consonants and other characters from a text

I need a program that asks the user to enter any text and then display three strings, the first of which consists of all the vowels from the text, the second, of all consonants, and the third, of all other characters. I have it in a while loop right now, I was wondering how I can transfer that into a for-loop in Python.

text = input("Enter text: ")

# Loop counter
i = 0

# Accumulators
vows_string = ""
cons_string = ""
other_str = ""

while i < len(text):
char = text[i]
if char in "aioueAIOUE":
vows_string += char
elif char.isalpha():
cons_string += char
other_str += char
i += 1

# Add pseudo-guillemets to make spaces "visible"
print(">>" + vows_string + "<<")
print(">>" + cons_string + "<<")
print(">>" + other_str + "<<")

Answer Source

Since strings are iterable, you can replace

while i < len(text):
    char = text[i]


for char in text:
    # no more need for 'i'

By the way, try if char.lower() in "aioue":