The isnumeric() method in Python is a built-in string method that checks whether a string consists only of numeric characters. It returns True if all the characters in the string are numeric, and False otherwise.
Syntax:
string.isnumeric()
How to use the isnumeric() method:
string1 = "12345"
print(string1.isnumeric()) # Output: True
string2 = "Hello123"
print(string2.isnumeric()) # Output: False
string3 = "12.5"
print(string3.isnumeric()) # Output: False
string4 = "①②③"
print(string4.isnumeric()) # Output: True
Example 1
Filter Numeric Strings from a List.
strings = ["123", "Hello", "456", "World", "789"]
numeric_strings = list(filter(lambda x: x.isnumeric(), strings))
print(numeric_strings) # Output: ['123', '456', '789']
Example 2
Extract Digits from a String using List Comprehension.
string = "Hello123World456"
digits = [int(char) for char in string if char.isnumeric()]
print(digits) # Output: [1, 2, 3, 4, 5, 6]
Example 3
Counting Digits in a String.
def count_digits(string):
count = 0
for char in string:
if char.isnumeric():
count += 1
return count
# Usage
string = "Hello123World456"
digit_count = count_digits(string)
print("Number of digits in the string:", digit_count)