I have a python list ['100', '20.0', '?', 'a', '0']
. The list contains real strings '?', 'a'
and ints and floats coded in strings. I am trying to find the (real) strings '?', 'a'
in the list.
Asked
Active
Viewed 176 times
-2
-
You want to check if the value is an alphanumeric character? – HamzaMushtaq Jul 08 '19 at 09:33
-
3What about strings `nan`, `-inf` etc.? They are valid floats in Python – Andrej Kesely Jul 08 '19 at 09:35
-
1Try to parse each element, catch errors and save those "invalid" values as your "real strings" – h4z3 Jul 08 '19 at 09:36
-
Yes I am trying to find all the elements (including nan and inf) that are not floats – kosa Jul 08 '19 at 09:37
-
2You have some useful answers and discussions on this topic in this question: https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float – locke14 Jul 08 '19 at 09:37
-
@locke14, Thankyou. This is what I am looking for. I can simply use `try` and `except`. – kosa Jul 08 '19 at 09:39
-
Should strings such as `a1` be counted? – TrebledJ Jul 08 '19 at 09:47
1 Answers
2
data = ['100', '20.0', '?', 'a', '0']
result = []
for item in data:
if not any(c.isnumeric() for c in item): # check if number exist in string
result.append(item)
print (result)
output:
['?', 'a']
what is equal to list comprehension:
print ([item for item in data if not any(c.isnumeric() for c in item) ])
output:
['?', 'a']

ncica
- 7,015
- 1
- 15
- 37