To check if a string contains only numeric digits in Python, you can use regular expressions or iterate through each character in the string and check if it is a digit using 'isdigit' method.
In this example,
import re
def containsOnlyNumericDigits(s):
return bool(re.match(r'^\d+$', s))
str = '12345'
allDigits = containsOnlyNumericDigits(str)
print('String contains only numeric digits:', allDigits)
String contains only numeric digits: True
In this example,
def containsOnlyNumericDigits(s):
return all(char.isdigit() for char in s)
str = '12345'
allDigits = containsOnlyNumericDigits(str)
print('String contains only numeric digits:', allDigits)
String contains only numeric digits: True
In this tutorial, we learned How to Check if String contains only Numeric Digits in Python language with well detailed examples.