Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string


The program takes an input string and counts the number of uppercase letters, lowercase letters, digits, and special characters in it. Here's a step by step explanation of the code:

  • The first line defines the input string "str".
  • The "print" statement outputs the original string to the console.
  • The next four lines define variables "upr", "lwr", "num", and "spl" to store the count of uppercase letters, lowercase letters, digits, and special characters respectively. They are initialized to 0.
  • The next block of code is a for loop that iterates over each character in the string "str".
  • The four "if" conditions inside the for loop check if the current character is an uppercase letter, lowercase letter, digit, or special character. If the character is an uppercase letter, the "upr" count is incremented by 1. If the character is a lowercase letter, the "lwr" count is incremented by 1. If the character is a digit, the "num" count is incremented by 1. If the character is a special character, the "spl" count is incremented by 1.
  • The next four "print" statements output the count of uppercase letters, lowercase letters, digits, and special characters to the console.

Source Code

str = "Hell0 W0rld ! 123 * #"
print("Original strings : ",str)
upr, lwr, num, spl = 0, 0, 0, 0
for i in range(len(str)):
	if str[i] >= 'A' and str[i] <= 'Z':
		upr += 1
	elif str[i] >= 'a' and str[i] <= 'z':
		lwr += 1
	elif str[i] >= '0' and str[i] <= '9':
		num += 1
	else:
		spl += 1
 
print("UpperCase : ",upr)
print("LowerCase : ",lwr)
print("NumberCase : ",num)
print("SpecialCase : ",spl)

Output

Original strings :  Hell0 W0rld ! 123 * #
UpperCase :  2
LowerCase :  6
NumberCase :  5
SpecialCase :  8


Example Programs