Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
counting vowels in a string
#1
Hi,

I'm moving from a C background to python. I'm trying to count the number of vowels in a string. I've put the vowels in a list, and I'm trying to see if the list's 1st vowel is found at a string position. If true, it logs it. If false, the string position is increased. This process continues until the string position matches the length of the string.

After this, the next vowel in the list is used, and the process starts over again.

This continues until all vowels have been tried.

In running the code, it only returns 0, so I'm not sure where my logic is going wrong.

Note that I had thought about using the string method, rindex(value, start, end), and then increasing the start and end values by 1 each pass (where they begin at start = 0, end = 1), and using the value as a reference to the vowel list, but I couldn't exclude the error handling of when a vowel wasn't found (i.e. pass over it).

Thoughts?

txt = "Count the number of vowels in this sentence."

#format: txt.rindex(value, start, end)

txt = ["a","e","i","o","u"] #vowels to test for

element = 0
counter = 0
position = 0


while position < len(txt) and element < len(txt):
    
    if txt[element] == txt[position] and position < len(txt):
        print("vowel counter = ", counter)
        position += 1 # inc list index position by 1
        
    else:
        # go to next vowel to search for
        # reset position to 0 to next vowel can be search for
        element += 1
        position = 0
        
print("Search complete, total vowels found: ", counter)
Reply
#2
A few things -
First you make txt equal to 'Count the number of vowels...'
You then immediately change the value of txt to the list of vowels.
Suggest - make the vowel string a different name. vowels maybe
Also, then make the vowel string 'aeiou' rather than quoted characters.
In line 14 part of your test is position < len(txt). Given your while statement this is always true and redundant
The rest of the comparison in line 14 is incorrect. txt[element] will equal txt[position] only when element equals position.
Reply
#3
Your program never increments counter, so it will remain at zero. But that's ok because your program never checks for how many vowels there are in a string. Where do you provide a string for counting? You don't. txt is initially set to a string, but shortly after it is set to the list of vowels.

You are writing a C program in Python. You should stop doing that. The more you stop doing that the faster you will learn Python.

You will find that while loops don't get used in Python nearly as much as for loops. The reason for this is Python allows almost any collection to be iterated, and for loops work really well with iterators while using iterators in a while loop is clunky. This is your program using a for loop to iterate through the text. I also made it a function so it is easily reused.
def vowels(txt):
    '''Return number of vowels in text'''
    count = 0
    for letter in txt.upper():
        count += letter in 'AEIOU' # Boolean True/False evaluate to 1/0 for math
    return count

print(vowels("Count the number of vowels in this sentence."))
This is a straight forward implementation, but you can probably do a lot better if you study the standard libraries. For example, this is a twist on your program that returns the count for each vowel in a dictionary.
from collections import Counter

def vowels(txt):
    '''Return number of vowels in text'''
    letters = Counter(txt.upper())
    return {key:value for key, value in letters.items() if key in 'AEIOU'}

print(vowels("Count the number of vowels in this sentence."))
It doesn't take very long to master the Python language, but mastering the language is just the tip of the iceberg. You also need to know the standard libraries to be an effective programmer. And then there is a load of programming conventions that are so ingrained that they are almost part of the language such as the use of underscores and double underscores and what each means and when it should be used.
Reply
#4
in addition to excellent advises from @jefsummers and @deanhystad - you can also use list comprehension

txt = "Count the number of vowels in this sentence."
vowels = "aeiouAEIOU"
cnt = sum(ch in vowels for ch in txt)
print(f'Number of vowels in the sentence is {cnt}')
Output:
Number of vowels in the sentence is 13
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  remove vowels in word with conditional ambrozote 12 4,088 May-02-2021, 06:57 PM
Last Post: perfringo
  Counting vowels in a string (PyBite #106) Drone4four 4 2,244 Jul-07-2020, 05:29 AM
Last Post: theknowshares
  Counting the number of letters in a string alphabetically TreasureDragon 2 2,883 Mar-07-2019, 01:03 AM
Last Post: TreasureDragon
  Counting number of characters in a string Drone4four 1 3,434 Aug-16-2018, 02:33 PM
Last Post: ichabod801
  no vowels function alex_bgtv 6 5,047 Jan-01-2018, 08:48 PM
Last Post: alex_bgtv
  replace vowels niru 9 20,709 Sep-26-2017, 12:46 PM
Last Post: nilamo
  Vowels and Consonants detector OmarSinno 5 9,762 Sep-21-2017, 02:27 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020