SixSigma
SixSigma

Reputation: 3260

How to check elements in list "are" numbers in Python?

Here is simple code:

s = ['-1', '2', '+']
print([x.isnumeric() for x in s])
print([x.isdigit() for x in s])

The output is

[False, True, False]
[False, True, False]

What I wish is:

[True, True, False]

Upvotes: 0

Views: 1021

Answers (4)

OShadmon
OShadmon

Reputation: 744

Using a for loop, and a replace you can easily check whether values in list are digits or not.

Example:

list = ['-1','2','+']
result=[]
for i in list:
        if '-' in i:
                result.append(i.replace('-','').isdigit())
        else:
                result.append(i.isdigit())

output:

>>> list = ['-1','2','+']
>>> result=[]
>>> for i in list:
...         if '-' in i:
...                 result.append(i.replace('-','').isdigit())
...         else:
...                 result.append(i.isdigit())
... 
>>> print result
[True, True, False]

For cases where the number is a float or decimal, you can easily add more if statements.

Upvotes: 0

Chris
Chris

Reputation: 22953

You could also use a regular expression pattern to match negative, positive, and decimal numbers:

>>> import re
>>> s = ['-1', '2', '+']
>>> [re.match('^(-|\+)?\d+(.\d+)?', n) is not None for n in s]
[True, True, False]
>>> 

Upvotes: 1

Paul Rooney
Paul Rooney

Reputation: 21609

Its a not a one liner but this works.

def isnum(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

s = ['-1', '2', '+']
print([isnum(x) for x in s])

Upvotes: 4

John Zwinck
John Zwinck

Reputation: 249273

[x.isnumeric() or (x[0] == '-' and x[1:].isnumeric()) for x in s]

Upvotes: 1

Related Questions