0

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?

Dan
  • 2,020
  • 5
  • 32
  • 55
  • 1
    `sys.version` ? – Axe319 Feb 12 '21 at 13:20
  • 1
    Does this answer your question? [How do I check what version of Python is running my script?](https://stackoverflow.com/questions/1093322/how-do-i-check-what-version-of-python-is-running-my-script) – Iron Fist Feb 12 '21 at 13:21
  • I prefer the `sys.version.major` if it's simply a difference between 2.xx vs 3.xx – astrochun Feb 12 '21 at 13:39
  • @Iron Fist yes, it helps alright. Glad to see there's a way to get the version but have to slot it nicely into the code. Cheers for the help – Dan Feb 12 '21 at 13:45
  • Be careful with `isdigit` and `isnumeric`: in addition to `0`-`9`, both functions also consider special Unicode characters as digits, such as `⑥` [U+2465 CIRCLED DIGIT SIX](https://unicode-explorer.com/c/2465)... – Flopp Jul 06 '21 at 12:31

2 Answers2

1

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
igrinis
  • 12,398
  • 20
  • 45
0

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()
frnknstn
  • 7,087
  • 1
  • 17
  • 18