Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Count the Vowels in a String

Python Count the Vowels in a String

Document Object Reference Manual Python3 Examples

In Python, we can count the vowels in a string by iterating over each character and checking whether it is a vowel (a, e, i, o, u). Here is a simple example.

Example

def

count_vowels

(

s

)

:

    vowels

=

"aeiouAEIOU"

    count

=

0

   

for

char

in

s:

       

if

char

in

vowels:

            count +

=

1

   

return

count

Example string

text

=

"Hello, World!"

print

(

f

"The number of vowels is: {count_vowels(text)}"

)

Code analysis:

  1. vowels = "aeiouAEIOU": Define a string containing all vowels, both uppercase and lowercase.
  2. count = 0: Initialize a counter to record the number of vowels.
  3. for char in s:: Iterate over each character in the string s .
  4. if char in vowels:: Check whether the current character is a vowel.
  5. count += 1: If it is a vowel, increment the counter by 1.
  6. return count: Return the final number of vowels.
  7. text = "Hello, World!": Define an example string.
  8. print(f"元音字母的数量是: {count_vowels(text)}"): Calling count_vowels function and print the result.

Output result:

元音字母的数量是: 3

Document Object Reference Manual Python3 Examples