Reputation: 39
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 + "<<")
Upvotes: 0
Views: 1207
Reputation: 41895
Now that the code is simple, let's make it potentially more efficient by using a set()
for the vowels instead of a string:
# Vowels Set
vowels = set("aeiouAEIOU")
# Accumulators
vowels_string = ""
consonants_string = ""
other_string = ""
# User Input
text = input("Enter text: ")
# Process Text
for char in text:
if char.isalpha():
if char in vowels:
vowels_string += char
else:
consonants_string += char
else:
other_string += char
# Add pseudo-guillemets to make spaces "visible"
print("<<", vowels_string, ">>", sep="")
print("<<", consonants_string, ">>", sep="")
print("<<", other_string, ">>", sep="")
Upvotes: 0
Reputation: 191844
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":
Upvotes: 2