Checking Digits in Python
Checking Digits in Python
In Python, you can check if a string represents a digit using the `isdigit()` method. This method
returns `True` if all the characters in the string are digits and there is at least one character, otherwise
it returns `False`. Here's how you can use it:
python
s = "12345"
if s.isdigit():
print(f"'{s}' is a digit.")
else:
print(f"'{s}' is not a digit.")
csharp
'12345' is a digit.
For a more comprehensive check that includes negative numbers and decimal points, you might use a
combination of checks or try to convert the string to a number:
python
s = "-12345"
try:
int(s)
print(f"'{s}' is an integer.")
except ValueError:
print(f"'{s}' is not an integer.")
python
s = "-123.45"
try:
float(s)
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/2
print(f"'{s}' is a float.")
except ValueError:
print(f"'{s}' is not a float.")
These approaches cover a wider range of numeric representations compared to the `isdigit()`
method.
ChatGPT can make mistakes. Check important info.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/2