w3resource

Python: Count Uppercase, Lowercase, special character and numeric values in a given string


Count uppercase, lowercase, special, numeric.

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

Visual Presentation:

Python String: Count Uppercase, Lowercase, special character and numeric values in a given string.

Sample Solution:

Python Code:

# Function to count character types
def count_chars(str):

  # Initialize counters
  upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0

  # Iterate through string
  for i in range(len(str)):

    # Increment appropriate counter 
    if str[i] >= 'A' and str[i] <= 'Z':
      upper_ctr += 1
    elif str[i] >= 'a' and str[i] <= 'z':
      lower_ctr += 1
    elif str[i] >= '0' and str[i] <= '9':
      number_ctr += 1
    else:
      special_ctr += 1

  # Return all counters
  return upper_ctr, lower_ctr, number_ctr, special_ctr

# Test string
str = "@W3Resource.Com"

# Print original string  
print("Original Substrings:",str)

# Call function and unpack counters
u, l, n, s = count_chars(str)

# Print counters
print('\nUpper case characters: ',u) 
print('Lower case characters: ',l)
print('Number case: ',n)
print('Special case characters: ',s) 

Sample Output:

Original Substrings: @W3Resource.Com

Upper case characters:  3
Lower case characters:  9
Number case:  1
Special case characters:  2

Flowchart:

Flowchart: Count Uppercase, Lowercase, special character and numeric values in a given string

For more Practice: Solve these Related Problems:

  • Write a Python program to count the number of uppercase, lowercase, numeric, and special characters in a string.
  • Write a Python program to use regular expressions to extract and count different character types from input text.
  • Write a Python program to iterate through a string and tally counts for each category using if-elif conditions.
  • Write a Python program to build a dictionary with keys 'uppercase', 'lowercase', 'digits', and 'special', and print the counts for a given string.

Go to:


Previous: Write a Python code to remove all characters except a specified character in a given string.
Next: Write a Python program to find the minimum window in a given string which will contain all the characters of another given string.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.