Suppose I have a list ['a', '1','student']
in Python
I am iterating through this list and want to check which item in the list is numeric.
I have tried all(item.isdigit())
, type(item)==str
. but shows error.
note: Numeric values in list are enclosed in quotes so they are identified as strings. How to get past that?
I am expecting to identify which item in list is numeric and which are alphabetical values. The challenge is the numeric values are enclosed in quotes identifying them as strings
CodePudding user response:
If you are after an array of bools, you can use:
lst = ['a', '1', 'student']
y = [x.isdigit() for x in lst]
>>> y
[False, True, False]
Where x.isdigit()
returns true if the string x
represents a digit. You can also use [x.isnumeric() for x in lst]
if you are after any string that is numeric. Which includes decimals.
CodePudding user response:
Try isdigit()
instead:
l = ['a', '1', 'student']
for item in l:
if item.isdigit():
print(f'{item} is a digit')
elif item.isalpha():
print(f'{item} is a letter')
CodePudding user response:
In the example you gave, extracting a list containing all the numbers is done by:
myList = ['a', '1','student']
onlyNumbers = [x for x in myList if x.isdigit()]
print(onlyNumbers)
An important distinction to make is the difference between a "number" type (int, float or Decimal) and a string that represents the number. If you had a list containing items of both string and integer types, then you could extract the items by altering the previous example like so:
myList = ['a', 1,'student']
onlyNumbers = [x for x in myList if isinstance(x,int)]
print(onlyNumbers)
Note how the 1 is no longer quoted. This means that it is a integer type.
Here are some recommendations:
all(iterable,condition)
returns a single value indicating whether ALL values in an iterable are true. It does not extract all values which are true, which is a misconception you appear to have.
Instead of type(x)==str
, you can do isinstance(x,str)
which is slightly cleaner.
To extract numbers from strings, you can use regular expressions. Alternatively, it is easier to attempt to convert the string to that number type:
anInteger = int("13")
aFloat = float("1") float("1.2")
aComplex = complex("1 1j")
This is an example to show it working in full. It relies on python's numeric types throwing an exception when a bad representation of that type is passed to the type's constuctor.
def isNumberType(repStr : str, numType):
try:
numType(repStr)
return True
except:
return False
x = ["12.32","12","ewa"]
onlyIntegers = [int(val) for val in x if isNumberType(val,int)]
print(onlyIntegers)
CodePudding user response:
You could use a regular expression:
import re
lst = ['a', '1', '100', 100,'student']
for item in lst:
if re.match(r'^\d $', str(item)):
print(item, 'is numeric')
elif item.isalpha():
print(item, 'is alphabetic')
Output:
a is alphabetic
1 is numeric
100 is numeric
100 is numeric
student is alphabetic