Home » Python » Python programs

Python program to input a string and find total number of letters and digits

Here, we are going to learn how to find the total number of letters and digits in a given string in Python programming language?
Submitted by IncludeHelp, on April 09, 2020

Given a string str1 and we have to count the total numbers of letters and digits.

Example:

    Input: 
    "Hello World!"
    Output:
    Letters: 10
    Digits: 0

    Input: 
    "[email protected]"
    Output:
    Letters: 5
    Digits: 3

Method 1:

(Manual) By checking each character of the string with a range of the letters and numbers using the conditional statement.

print("Input a string: ")
str1 = input()

no_of_letters, no_of_digits = 0,0

for c in str1:
    if (c>='a' and c<='z') or (c>='A' and c<='Z'):
        no_of_letters += 1
    if c>='0' and c<='9':
        no_of_digits += 1

print("Input string is: ", str1)
print("Total number of letters: ", no_of_letters)
print("Total number of digits: ", no_of_digits)

Output

RUN 1:
Input a string: 
Hello World!
Input string is:  Hello World!
Total number of letters:  10
Total number of digits:  0

RUN 2:
Input a string: 
[email protected]
Input string is:  [email protected]
Total number of letters:  5
Total number of digits:  3

Method 2:

By using isalpha() and isnumeric() methods

print("Input a string: ")
str1 = input()

no_of_letters, no_of_digits = 0,0

for c in str1:
  no_of_letters += c.isalpha()
  no_of_digits += c.isnumeric()

print("Input string is: ", str1)
print("Total number of letters: ", no_of_letters)
print("Total number of digits: ", no_of_digits)

Output

RUN 1:
Input a string: 
Hello World!
Input string is:  Hello World!
Total number of letters:  10
Total number of digits:  0

RUN 2:
Input a string: 
[email protected]
Input string is:  [email protected]
Total number of letters:  5
Total number of digits:  3





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.