Tuesday, July 30, 2019

Count characters, digits, uppercase and lowercase in a string

Script

#!/usr/local/bin/python3

print()
string1 = "Rahul Dravid scored 233 and 72 not out to win the 2003-04 Adelaide Test for India by 4 wickets."
digitCount = 0
alphabetCount = 0
uppercaseCount = 0
lowercaseCount = 0

for x in range(0, len(string1)):
    char = string1[x]
    if (char.isdigit()):
        digitCount += 1
    elif (char.isalpha()):
        alphabetCount += 1
        if (char.upper() == char):
            uppercaseCount += 1
        else:
            lowercaseCount += 1

print("Original string: ", string1)
print("Number of digits = ", digitCount)
print("Number of alphabets = ", alphabetCount)
print("Number of uppercase characters = ", uppercaseCount)
print("Number of lowercase characters = ", lowercaseCount)
print()


Execution

Original string:  Rahul Dravid scored 233 and 72 not out to win the 2003-04 Adelaide Test for India by 4 wickets.
Number of digits =  12
Number of alphabets =  63
Number of uppercase characters =  5
Number of lowercase characters =  58





No comments:

Post a Comment