Conor Conor - 29 days ago 7
Python Question

How to split text in Python

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
else:
other_str += char
i += 1

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

Answer

Since strings are iterable, you can replace

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

with

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

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