0% found this document useful (0 votes)
14 views

Checking Digits in Python

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Checking Digits in Python

Uploaded by

Elliot Lassey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Checking Digits in Python

how to check if something is a digit 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.")

This will output:

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:

For integer values (including negative numbers):

python

s = "-12345"
try:
int(s)
print(f"'{s}' is an integer.")
except ValueError:
print(f"'{s}' is not an integer.")

For floating-point numbers:

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

You might also like