Reputation: 2172
I have a list containing strings. These strings are either words or integer values. For example this list might look like this:
['0', 'Negate', '-3', '2', 'SPECIALCASE', '3']
Now, based on their type (integer or string), I want to treat them differently. However, as you have noticed I can't use isinstace()
. I can still use type()
and try to convert the integer values using the int()
function and put the whole thing in a try-except method to avoid raising errors for the conversion of words. But this seems hackish to me. Do you know the right way of handling this case? Thanks in advance!
Upvotes: 1
Views: 266
Reputation: 4006
For reference, here's a regex approach. This may be overkill.
mylist = ['0', 'Negate', '-3', '2', 'SPECIALCASE', '3']
import re
p = re.compile(r'-?\d+')
[p.match(e) is not None for e in mylist]
# returns [True, False, True, True, False, True]
This returns a list with True
for any strings that optionally start with a -
, then contain one or more digits; False
for any other strings.
Or if you don't need a list but just want to perform different operations:
for item in mylist:
if p.match(item):
# it's a number
else:
# it's a string
The above works becasue None
(i.e. no match) evaluates to False
and anything else (when it comes to regex matches) evaluates to True
. If you want to be more explicit you can use if p.match(item) is not None:
.
Upvotes: 0
Reputation: 4467
You can just use type conversion to check whether it's an integer or string,
def is_integer(input):
try:
int(input)
return True
except:
return False
for item in ['0', 'Negate', '-3', '2', 'SPECIALCASE', '3']:
if is_integer(item):
...
else:
...
Upvotes: 0
Reputation: 22679
A pythonic way of "Don't ask permission, ask for forgiveness":
lst = ['0', 'Negate', '-3', '2', 'SPECIALCASE', '3']
for item in lst:
try:
int_number = int(item)
except ValueError:
# handle the special case here
Note, that this should be done if you expect that only few items in the list are going to be the 'special' case items. Otherwise do the checks as @doomster advices.
Upvotes: 3
Reputation: 17444
I'd take a different approach. If you know all possible "special" words, check for these. Everything else must be an int:
keywords = {'Negate', 'SPECIALCASE'}
tmp = []
for i in lis:
if i in keywords:
tmp.append(i)
else
tmp.append(int(i))
Of course, if you want to accept anything but ints without conversion, then trying to convert and falling back to unconverted use is the way to go.
Upvotes: 3