The isdigit()
method in Python is used to check whether a string contains only digits (numeric characters). It returns True
if all the characters in the string are digits (0-9), and there is at least one character in the string. Otherwise, it returns False
.Here's the syntax of the isdigit()
method:
string.isdigit()
# Examples of isdigit() method
string1 = "12345"
string2 = "123.45"
string3 = "Hello"
result1 = string1.isdigit()
result2 = string2.isdigit()
result3 = string3.isdigit()
print("String 1:", string1)
print("String 2:", string2)
print("String 3:", string3)
print("isdigit() result for String 1:", result1)
print("isdigit() result for String 2:", result2)
print("isdigit() result for String 3:", result3)
String 1: 12345
String 2: 123.45
String 3: Hello
isdigit() result for String 1: True
isdigit() result for String 2: False
isdigit() result for String 3: False
In this example, string1
contains only digits ("12345"), so isdigit()
returns True
. string2
contains a decimal point, so it is not composed entirely of digits, and thus isdigit()
returns False
. string3
contains letters ("Hello"), so it is also not composed of digits, and isdigit()
returns False
.
The isdigit()
method is useful when you want to ensure that a string contains only numeric characters, such as when processing user input that should be in a numerical format or checking if a string can be converted to a numeric type.