Python Different Counts in String

By | January 12, 2023

Python Different Counts in String – Python program to count uppercase letters, lower case letters, vowels, consonants and spaces in the given string.

Python Different Counts in String

 

#Python program to count upper case letters, lower case letters
#vowels, consonants and spaces in a string

uppercase=0
lowercase=0
vowels=0
consonants=0
spaces=0

string=input("Enter a String: ")

for ch in  string:
    if (ch.isupper()):
        uppercase+=1

    if (ch.islower()):
        lowercase+=1
    if (ch in ('A', 'a', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')):
        vowels+=1
    elif (ch.isalpha()):
        consonants+=1
    if (ch.isspace()):
        spaces+=1

print("The given string contains...")
print("%d Uppercase letters"%uppercase)
print("%d Lowercase letters"%lowercase)
print("%d Vowels"%vowels)
print("%d Consonants"%consonants)
print("%d Spaces"%spaces)

The Python program provides many conts of different types in a string. For example it will display the number of

  • Uppercase letters
  • Lowercase letters
  • Vowels
  • Consonants
  • and Spaces

Output: Here is some sample output of this program run.

Enter a String: Hello World
The given string contains…
2 Uppercase letters
8 Lowercase letters
3 Vowels
7 Consonants
1 Spaces

Explanation of key parts of the program:

  1. A series of variables (uppercase, lowercase, vowels, consonants, and spaces) are initialized to store the counts of different character types.
  2. The input() function is used to take user input for the string that needs to be analyzed.
  3. A for loop iterates through each character (ch) in the input string.
  4. Inside the loop:
    • The isupper() method is used to check if the current character is in uppercase, and if so, the uppercase counter is incremented.
    • The islower() method is used to check if the current character is in lowercase, and if so, the lowercase counter is incremented.
    • A tuple containing the lowercase and uppercase vowels is used to check if the character is a vowel. If it is, the vowels counter is incremented.
    • The isalpha() method is used to check if the character is an alphabetic character (i.e., not a digit or special character), and if so, the consonants counter is incremented.
    • The isspace() method is used to check if the character is a space, and if so, the spaces counter is incremented.
  5. After the loop completes, the program prints the counts of each type of character based on the gathered data.

The program’s purpose is to provide insights into the composition of characters within the input string, helping the user understand the distribution of uppercase letters, lowercase letters, vowels, consonants, and spaces.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *