Reputation: 91660
In case anyone is interested, this is a followup to Regular expression to match a Python integer literal.
The tokenize
module is useful for breaking apart a Python expression, but tokenize.NUMBER
is not very expressive, as it represents all kinds of number literals, for example, 1
, 1l
(in Python 2), 0xf2
, 1e-10
, 1.1
, 0b101
, 0o17
, and 1j
are all considered NUMBER (and also all the previous with uppercase letters). Is there a function in the standard library that tells me what kind of the above I have? I particularly care about if I have an integer or a float (complex is also considered float), but further expressiveness would be OK too :). Basically, I don't want to try to catch all possible number literals myself, as I already managed to do it wrong once.
Upvotes: 2
Views: 392
Reputation: 104092
You can use ast.literal_eval to parse any Python number format down to an int, float, or long:
>>> ast.literal_eval('1')
1
>>> ast.literal_eval('1l')
1L
>>> ast.literal_eval('0x2')
2
>>> ast.literal_eval('0b1101')
13
Bear in mind that there is no 'hex' or 'oct' or 'bin' type in Python. Those literal strings are immediately converted to their decimal equivalents.
This works pretty well:
def numtype(s):
numtypes=[int,long,float,complex]
try:
n=ast.literal_eval(s)
except SyntaxError:
return None
if type(n) not in numtypes:
return None
else:
return type(n)
for t in ['1','0x1','0xf2','1e-10','0o7','1j', '0b1101']:
print t, numtype(t)
Prints:
1 <type 'int'>
0x1 <type 'int'>
0xf2 <type 'int'>
1e-10 <type 'float'>
0o7 <type 'int'>
1j <type 'complex'>
0b1101 <type 'int'>
If you really need to differentiate between the different decimal types, you could do something like:
def numtype(s):
numtypes=[int,long,float,complex]
try:
n=ast.literal_eval(s)
except SyntaxError:
return None
if type(n) not in numtypes:
return None
if type(n) != int:
return type(n)
else:
if 'x' in s.lower():
return 'HEX'
if 'o' in s.lower():
return 'OCT'
if 'b' in s.lower():
return 'BIN'
return int
Upvotes: 3
Reputation: 308530
def is_int(number_string):
try:
i = int(number_string)
except ValueError:
return False
return True
Upvotes: 0