Home » Python » Python programs

Python program to check whether a string contains a number or not

Python isdigit() function example: Here, we are going to learn how to check whether a string contains only digits or not i.e. string contains only number or not?
Submitted by IncludeHelp, on April 07, 2019

Given a string and we have to check whether it contains only digits or not in Python.

To check that a string contains only digits (or a string has a number) – we can use isdigit() function, it returns true, if all characters of the string are digits.

Syntax:

    string.isdigit()

Example:

    Input:
    str1 = "8789"
    str2 = "Hello123"
    str3 = "123Hello"
    str4 = "123 456" #contains space 

    # function call
    str1.isdigit()
    str2.isdigit()
    str3.isdigit()
    str4.isdigit()

    Output:
    True
    False
    False
    False

Python code to check whether a strings contains a number or not

# python program to check whether a string 
# contains only digits or not 

# variables declaration & initializations
str1 = "8789"
str2 = "Hello123"
str3 = "123Hello"
str4 = "123 456"    #contains space 

# checking
print("str1.isdigit(): ", str1.isdigit())
print("str2.isdigit(): ", str2.isdigit())
print("str3.isdigit(): ", str3.isdigit())
print("str4.isdigit(): ", str4.isdigit())

# checking & printing messages
if str1.isdigit():
    print("str1 contains a number")
else:
    print("str1 does not contain a number")

if str2.isdigit():
    print("str2 contains a number")
else:
    print("str2 does not contain a number")

if str3.isdigit():
    print("str3 contains a number")
else:
    print("str3 does not contain a number")

if str4.isdigit():
    print("str4 contains a number")
else:
    print("str4 does not contain a number")

Output

str1.isdigit():  True
str2.isdigit():  False
str3.isdigit():  False
str4.isdigit():  False
str1 contains a number
str2 does not contain a number
str3 does not contain a number
str4 does not contain a number





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







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.