Search code examples
pythonstringcountord

How can I make it shorter and better?


I have an assignment about strings in loop and I need to find out how many (a,e,i,o,u) in the input . I have done it but I think it's too long. I want to make it shorter but I have no idea how.

This is my code:

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:")

a=len(x)

x1=0

x2=0

x3=0

x4=0

x5=0

for i in range(a):
    h=ord(x[i])

    if h == 105:
        x1+=1
    elif h == 111: 
        x2+=1
    elif h == 97:
        x3+=1
    elif h == 117:
        x4+=1
    elif h == 101:
        x5+=1

print("There were",x3,"'a's")
print("There were",x5,"'e's")
print("There were",x1,"'i's")
print("There were",x2,"'o's")
print("There were",x4,"'u's")

Solution

  • Simple approach according to this question:

    x = input("Enter the text that you need me to count how many (a,e,i,o,u) are in it:")
    
    print("There were", x.count('a'), "'a's")
    print("There were", x.count('e'), "'e's")
    print("There were", x.count('i'), "'i's")
    print("There were", x.count('o'), "'o's")
    print("There were", x.count('u'), "'u's")