1

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!

3
  • 1
    "try to convert the integer values using the int() function " - that's the way to go or you use a regular expression...
    – user2665694
    Commented Jan 13, 2013 at 12:38
  • the best way to do this very much depends on what you want the final result to be, how do you want '-3' to be handled? should that be an int? what if you have 2.45 should that be a string or a number? should it be converted to a float or an int? probably your best shot should be try/except unless you want to go into bitwise checks.
    – Inbar Rose
    Commented Jan 13, 2013 at 12:38
  • 1
    You say you want to treat them differently based on type, but is that what you really want? Python isn't designed for type-checking, it's designed as a duck-typed language. Do what you want based on if the object can do it not what type it is. Commented Jan 13, 2013 at 12:39

4 Answers 4

3

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.

3

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.

1
  • 1
    +1, a good approach if possible (although if the keywords are very rare, it might be sub-optimal). The building of the list could, however, be simplified to a list comprehension: tmp = [i if i in keywords else int(i) for i in lis] Commented Jan 13, 2013 at 13:06
0

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:
     ...
1
  • 2
    Don't use except without specifying the exception, it can hide bugs and make it extremely hard to find problems. Commented Jan 14, 2013 at 7:21
0

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:.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.