Counting the number of vowels in a string using for loops in Python

2024/9/20 17:57:52

Python Code:

sentence = input('Enter a string:')
vowel = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for vowel in sentence:Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

I am trying to write a program that prompts the user to enter a string. The program then returns the number of vowels in the string. However, the code just returns the number of letters, without regard for just giving back vowels.

Answer

I think the best way is to use a simple RegEx. The RegEx to match a vowel is [aeiou] (or [aeiouy] if you want to match "y" too).

You can use re.findall to find all occurences of a vowel in a sentence, use the re.IGNORECASE flag to ignore case.

>>> import re
>>> sentence = "my name is Jessica"
>>> len(re.findall(r'[aeiou]', sentence, flags=re.IGNORECASE))
6

The advantage of this solution is that you can extend it easily to add accentuated characters or other unicode character:

>>> import re
>>> sentence = "Dès Noël où un zéphyr haï me vêt de glaçons würmiens je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera !"
>>> len(re.findall(r'[aeiouyàâèéêëiïîöôüûùæœÿ]', sentence, flags=re.IGNORECASE))
41
https://en.xdnf.cn/q/119307.html

Related Q&A

Sum the values of specific rows if the rows have same values in specific column

I have a data frame like this:a b c 12456 11 123.1 12678 19 345.67 13278 19 1235.345or in another format <table><tr><td>12456</td><td>11</td><td>1…

Plotting Interpolated 3D Data As A 2D Image using Matplotlib

The data set is made of a list dfList containing pandas DataFrames, each DataFrame consisting of the column Y and an identical index column. I am trying to plot all the DataFrames as a 2D plot with pix…

Plotting a flow duration curve for a range of several timeseries in Python

Flow duration curves are a common way in hydrology (and other fields) to visualize timeseries. They allow an easy assessment of the high and low values in a timeseries and how often certain values are …

HTML variable value is not changing in Flask

I have written this code in Flaskans = 999 @app.route(/, methods=[POST, GET]) def home():flag = 0global anssession["ans"] = 0if (request.method == "POST"):jsdata = request.form[data…

How to add two lists with the same amount of indexs in python

I am still new to coding so i apologize for the basic question. How do I add to elements of two seperate lists? listOne = [0, 1 , 7, 8] listTwo = [3, 4, 5, 6] listThree = []for i in listOne:listAdd = …

How to crawl thousands of pages using scrapy?

Im looking at crawling thousands of pages and need a solution. Every site has its own html code - they are all unique sites. No clean datafeed or API is available. Im hoping to load the captured data i…

Object Transmission in Python using Pickle [duplicate]

This question already has answers here:Send and receive objects through sockets in Python(3 answers)Closed last year.I have the following class, a Point objectclass Point:def __init__(self):passdef __i…

Google App Engine: Modifying 1000 entities

I have about 1000 user account entities like this:class UserAccount(ndb.Model):email = ndb.StringProperty()Some of these email values contain uppercase letters like [email protected]. I want to select …

more efficient method of dealing with large numbers in Python? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

MLM downline distribution count

I make my first MLM software and I think I managed to code how to get the points from the downline even though it is a recursive problem I didnt use recursion and I might refactor to a recursive versio…