Dan
Dan

Reputation: 2100

Using isnumeric in both Python2 and 3

Working on an application that has a function that takes in a value and I am trying to see if it is an int, float or string. After doing some looking online I found isnumeric() and isdigit() to cover both int and float scenarios and string is default.

Brilliant... problem solved :)

Well not quite! Because this app supports Python versions 2.7.15, 3.4.8, 3.5.5, 3.6.6 and I learned that for Python 2 isnumeric and isdigit works on unicode while Python 3 it works on strings.

So I have my CI passing the tests for Python 3 but failing for Python 2 :(

Is there a way to check what version of Python is being ran dynamically and from there use the correct implementation of the functions?

Upvotes: 0

Views: 1392

Answers (2)

frnknstn
frnknstn

Reputation: 7635

For easy cross-version portability of unicode methods, you need to set unicode to be an alias of str on Python 3.

if sys.version_info.major == 3:
    # Python 3
    unicode = str

def isnumeric(s):
    return unicode(s).isnumeric()

Upvotes: 0

igrinis
igrinis

Reputation: 13626

First, you can use isalpha() and isdigit() on strings also with Python 2.x. Second you can try to convert a variable to float and int and see if the action throws exception.

for x in ['aa', '2.3', '4']:
  try:
    x = int(x)
    print x, ' is integer'
    continue
  except:
    pass    

  try:
    x = float(x)
    print x, 'is float'
    continue
  except:
    pass

  print x, 'is string'



aa is string
2.3 is float
4  is integer

Upvotes: 1

Related Questions