Skip to content

Python isdigit negative

  • by

Python isdigit() function can’t check negative numbers because this method tests for digits only, and - is not a digit. Use lstrip to remove - or use int() to catch the ValueError exception instead if you wanted to detect integers:

value.lstrip("-").isdigit()

Python isdigit negative example

A simple example code converts all numbers into integers using the .isdigit() method

mylist = ["name", "test", "1", "3", "-3", "name"]
print(mylist)

for i in range(len(mylist)):
    try:
        mylist[i] = int(mylist[i])
    except ValueError:
        pass
print(mylist)

Output:

Python isdigit negative

Use lstrip() function first. This will work for positive and negative numbers.

str = "-2137"

res = str.lstrip('-').isdigit()
print(res)

Output: True

Do comment if you have any doubts or suggestions on this Python isdigit topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading