What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling float in the main function is even worse.

share|improve this question
26  
What's wrong with what your current solution? It's short, fast and readable. – Colonel Panic Mar 21 '13 at 22:52
3  
And you don't just have to return True or False. You can return the value suitably modified instead - for example you could use this to put non-numbers in quotes. – Thruston May 24 '13 at 21:33
5  
Wouldn't it better to return the result of float(s) in the case of a successful conversion? You still have the check for success (result is False) and you actually HAVE the conversion, which you are likely to want anyway. – Jiminion Jul 25 '13 at 14:40
6  
Even though this question is older, I just wanted to say that this is an elegant way which is documented as EAFP. So probably the best solution for this kind of problem. – thiruvenkadam Oct 7 '13 at 15:42
4  
Don't return the result of float(s) or None on fail. if you then use it as x = float('0.00'); if x: use_float(x); you've now got a bug in your code. Truthy values are the reason these functions raise an exception rather than returning None in the first place. A better solution is just to avoid the utility function and surround the call to float in a try catch when you want to use it. – ovangle Jan 5 '16 at 7:31

29 Answers 29

up vote 516 down vote accepted

Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (e.g., via errno) or exception to show that no valid number could be parsed.

C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

I think your code for doing this is perfect.

share|improve this answer
12  
I don't think that the code is perfect (but I think it's very close): it is more usual to put only the part being "tested" in the try clause, so I would put the return True in an else clause of the try. One of the reasons is that with the code in the question, if I had to review it, I would have to check that the second statement in the try clause cannot raise a ValueError: granted, this does not require too much time or brain power, but why use any when none is needed? – EOL Jul 5 '13 at 8:21
3  
The answer seems compelling, but makes me wonder why it's not provided out-of-the-box... I'll copy this and use it in any case. – sage Dec 28 '13 at 23:40
3  
How awful. How about if I don't care what the number is just that it's a number (which is what brought me here)? Instead of a 1-line IsNumeric() I either end up with a try/catch or another wrapping a try/catch. Ugh – Basic Mar 10 '14 at 11:22
2  
@Basic I do not get your point. Name your function, which does the checking IsNumeric and use that function. Thats the idea of using functions - having one-liners. – Nils Mar 12 '14 at 20:38
3  
It's not provided 'out of the box' because if is_number(s): x = float(x) else: // fail is the same number of lines of code as the try: x = float(x) catch TypeError: # fail. This utility function is an entirely unecessary abstraction. – ovangle Jan 5 '16 at 7:34

For strings of non-numbers, try: except: is actually slower than regular expressions. For strings of valid numbers, regex is slower. So, the appropriate method depends on your input.

If you find that you are in a performance bind, you can use a new third-party module called fastnumbers that provides a function called isfloat. Full disclosure, I am the author. I have included its results in the timings below.


from __future__ import print_function
import timeit

prep_base = '''\
x = 'invalid'
y = '5402'
z = '4.754e3'
'''

prep_try_method = '''\
def is_number_try(val):
    try:
        float(val)
        return True
    except ValueError:
        return False

'''

prep_re_method = '''\
import re
float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match
def is_number_re(val):
    return bool(float_match(val))

'''

fn_method = '''\
from fastnumbers import isfloat

'''

print('Try with non-number strings', timeit.timeit('is_number_try(x)',
    prep_base + prep_try_method), 'seconds')
print('Try with integer strings', timeit.timeit('is_number_try(y)',
    prep_base + prep_try_method), 'seconds')
print('Try with float strings', timeit.timeit('is_number_try(z)',
    prep_base + prep_try_method), 'seconds')
print()
print('Regex with non-number strings', timeit.timeit('is_number_re(x)',
    prep_base + prep_re_method), 'seconds')
print('Regex with integer strings', timeit.timeit('is_number_re(y)',
    prep_base + prep_re_method), 'seconds')
print('Regex with float strings', timeit.timeit('is_number_re(z)',
    prep_base + prep_re_method), 'seconds')
print()
print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with integer strings', timeit.timeit('isfloat(y)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print('fastnumbers with float strings', timeit.timeit('isfloat(z)',
    prep_base + 'from fastnumbers import isfloat'), 'seconds')
print()

Try with non-number strings 2.39108395576 seconds
Try with integer strings 0.375686168671 seconds
Try with float strings 0.369210958481 seconds

Regex with non-number strings 0.748660802841 seconds
Regex with integer strings 1.02021503448 seconds
Regex with float strings 1.08564686775 seconds

fastnumbers with non-number strings 0.174362897873 seconds
fastnumbers with integer strings 0.179651021957 seconds
fastnumbers with float strings 0.20222902298 seconds

As you can see

  • try: except: was fast for numeric input but very slow for an invalid input
  • regex is very efficient when the input is invalid
  • fastnumbers wins in both cases
share|improve this answer
1  
@Alfe If you re-read the code you will see that it is already doing both of those things. – SethMMorton Apr 22 '16 at 14:43
    
I stand corrected :-} it just didn't look like it was doing this. Maybe using names like prep_code_basis and prep_code_re_method would have prevented my mistake. – Alfe Apr 22 '16 at 20:11
1  
@Alfe Please fell free to edit this answer if you want to make it more clear. – SethMMorton Apr 26 '16 at 16:19
    
Do you mind explaining how your module works, at least for the isfloat function? – Solomon Ucko May 4 '16 at 23:33
    
@SolomonUcko Here is a link to the source code for the string checking part: github.com/SethMMorton/fastnumbers/blob/v1.0.0/src/…. Basically, it walks across each character in the string in order and validates that it follows a pattern for a valid float. If the input is already a number, it just uses the fast PyFloat_Check. – SethMMorton May 5 '16 at 0:15

TL;DR The best solution is s.replace('.','',1).isdigit()

I did some benchmarks comparing the different approaches

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

import re    
def is_number_regex(s):
    """ Returns True is string is a number. """
    if re.match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

If the string is not a number, the except-block is quite slow. But more importantly, the try-except method is the only approach that handles scientific notations correctly.

funcs = [
          is_number_tryexcept, 
          is_number_regex,
          is_number_repl_isdigit
          ]

a_float = '.1234'

print('Float notation ".1234" is not supported by:')
for f in funcs:
    if not f(a_float):
        print('\t -', f.__name__)

Float notation ".1234" is not supported by:
- is_number_regex

scientific1 = '1.000000e+50'
scientific2 = '1e50'


print('Scientific notation "1.000000e+50" is not supported by:')
for f in funcs:
    if not f(scientific1):
        print('\t -', f.__name__)




print('Scientific notation "1e50" is not supported by:')
for f in funcs:
    if not f(scientific2):
        print('\t -', f.__name__)

Scientific notation "1.000000e+50" is not supported by:
- is_number_regex
- is_number_repl_isdigit
Scientific notation "1e50" is not supported by:
- is_number_regex
- is_number_repl_isdigit

EDIT: The benchmark results

import timeit

test_cases = ['1.12345', '1.12.345', 'abc12345', '12345']
times_n = {f.__name__:[] for f in funcs}

for t in test_cases:
    for f in funcs:
        f = f.__name__
        times_n[f].append(min(timeit.Timer('%s(t)' %f, 
                      'from __main__ import %s, t' %f)
                              .repeat(repeat=3, number=1000000)))

where the following functions were tested

from re import match as re_match
from re import compile as re_compile

def is_number_tryexcept(s):
    """ Returns True is string is a number. """
    try:
        float(s)
        return True
    except ValueError:
        return False

def is_number_regex(s):
    """ Returns True is string is a number. """
    if re_match("^\d+?\.\d+?$", s) is None:
        return s.isdigit()
    return True


comp = re_compile("^\d+?\.\d+?$")    

def compiled_regex(s):
    """ Returns True is string is a number. """
    if comp.match(s) is None:
        return s.isdigit()
    return True


def is_number_repl_isdigit(s):
    """ Returns True is string is a number. """
    return s.replace('.','',1).isdigit()

enter image description here

share|improve this answer
1  
Please include the results in your post... not a link. – Erik Aronesty Oct 3 '16 at 14:21
    
just added them – Sebastian Oct 3 '16 at 20:14
1  
for nice charts +1. I saw benchmark and saw graph, all the TL;DR thing became clear and intuitive. – Julian Chukwu Nov 18 '16 at 18:35
    
I agree with @JCChuks: the graph helps a lot to get all the TL;DR quickly. But I think a TL;DR (like : TL;DR : the best solution is s.replace('.','',1).isdigit()) should appear at the beginning of this anwser. In any case it should be the accepted one. Thanks! – Simon C. Mar 10 '17 at 9:59

I know this is particularly old but I would add an answer I believe covers the information missing from the highest voted answer that could be very valuable to any who find this:

For each of the following methods connect them with a count if you need any input to be accepted. (Assuming we are using vocal definitions of integers rather than 0-255, etc.)

x.isdigit() works well for checking if x is an integer.

x.replace('-','').isdigit() works well for checking if x is a negative.(Check - in first position)

x.replace('.','').isdigit() works well for checking if x is a decimal.

x.replace(':','').isdigit() works well for checking if x is a ratio.

x.replace('/','',1).isdigit() works well for checking if x is a fraction.

share|improve this answer
1  
Though for fractions, you probably need to do x.replace('/','',1).isdigit() or otherwise dates such as 4/7/2017 would be misinterpreted as numbers. – Yuxuan Chen Apr 7 '17 at 14:06

use following it handles all cases:-

import re
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3') 
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '.3')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3sd')
a=re.match('((\d+[\.]\d*$)|(\.)\d+$)' ,  '2.3')
share|improve this answer

I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:

def is_float(text):
    try:
        float(text)
        # check for nan/infinity etc.
        if text.isalpha():
            return False
        return True
    except ValueError:
        return False
share|improve this answer

To check if the input value is a float, you can compare the type of the input to a float

def isFloat(s):
    realFloat = 0.1

    if type(s) == type(realFloat):
        return True
    else:
        return False

Returns:

False     # s = 5
True      # s = 1.2345

The original post would actually return True for s = 5 since it is a number (integer) and you can cast an int to a float without a ValueError. If you are trying to verify that it is an actual float instead of just a number, you would need to account for that case.

share|improve this answer

Updated after Alfe pointed out you don't need to check for float separately as complex handles both:

def is_number(s):
    try:
        complex(s) # for int, long, float and complex
    except ValueError:
        return False

    return True

Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:

def is_number(s):
    try:
        float(s) # for int, long and float
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False

    return True
share|improve this answer
13  
I disagree. That's VERY unlikely in normal use, and you would be better building an is_complex_number() call for when you are using them, rather than burden a call with extra operation for a 0.0001% chance of misoperation. – Jiminion Jul 25 '13 at 14:43
3  
You can strip the float() stuff completely and just check for the complex() call to succeed. Everything parsed by float() can be parsed by complex(). – Alfe Apr 22 '16 at 9:31
1  
Good point @Alfe - answer updated to reflect your comment. – Matthew Wilcoxson Apr 22 '16 at 15:43
    
This function will return Pandas's NaNs and Inf values as numeric values. – fixxxer May 29 '16 at 11:51

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

String Methods - isdigit()

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

share|improve this answer
61  
However, this won't work for Hexadecimal. – Nico Dec 9 '08 at 20:17
166  
Nor does it work for numbers with decimal places like 1.2 – Daniel Goldberg Dec 9 '08 at 21:48
187  
That's a negative on negatives as well – intrepion Oct 23 '09 at 7:05
46  
@DanielGoldberg: I think you need to go lookup the definition of "digit" – Jason9987 Sep 24 '11 at 22:05
130  
@Jason9987, it seems you need to reread the question. – Daniel Goldberg Oct 13 '11 at 17:42

For int use this:

>>> "1221323".isdigit()
True

But for float we need some tricks ;-). Every float number has one point...

>>> "12.34".isdigit()
False
>>> "12.34".replace('.','',1).isdigit()
True
>>> "12.3.4".replace('.','',1).isdigit()
False

Also for negative numbers just add lstrip():

>>> '-12'.lstrip('-')
'12'

And now we get a universal way:

>>> '-12.34'.lstrip('-').replace('.','',1).isdigit()
True
>>> '.-234'.lstrip('-').replace('.','',1).isdigit()
False
share|improve this answer
1  
Doesn't handle things like 1.234e56 and similar. Also, I'd be interested how you'd find out that 99999999999999999999e99999999999999999999 is not a number. Trying to parse it finds out quickly. – Alfe Apr 22 '16 at 9:37
    
This runs ~30% faster than the accepted solution on a list of 50m strings, and 150% faster on a list of 5k strings. 👏 – Zev Averbach Feb 21 '17 at 13:59

You may use regex.

number = raw_input("Enter a number: ")
if re.match(r'^\d+$', number):
    print "It's integer"
    print int(number)
elif re.match(r'^\d+\.\d+$', number):
    print "It's float"
    print float(number)
else:
    print("Please enter a number")
share|improve this answer

Try this.

 def is_number(var):
    try:
       if var == int(var):
            return True
    except Exception:
        return False
share|improve this answer
    
Fails to respond with is_number('10') – geotheory Aug 18 '15 at 20:23
    
@geotheory, what do you mean "fails to respond"? – Solomon Ucko May 4 '16 at 23:38
    
Returns nothing – geotheory May 5 '16 at 1:34

I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways:

1 - I wanted an integer result if the string represented an integer

2 - I wanted a number or a string result to stick into a data structure

so I adapted the original code to produce this derivative:

def string_or_number(s):
    try:
        z = int(s)
        return z
    except ValueError:
        try:
            z = float(s)
            return z
        except ValueError:
            return s
share|improve this answer

Lets say you have digits in string. str = "100949" and you would like to check if it has only numbers

if str.isdigit():
returns TRUE or FALSE 

isdigit docs

otherwise your method works great to find the occurrence of a digit in a string.

share|improve this answer
    
Isn't this the same answer as the answer by @Zoomulator from six years ago? – PJvG Oct 13 '14 at 9:26
2  
Ahh too many answers here, i saw the top few and played my part. Cheers. – Clayton Oct 13 '14 at 9:34

I needed to determine if a string cast into basic types (float,int,str,bool). After not finding anything on the internet I created this:

def str_to_type (s):
    """ Get possible cast type for a string

    Parameters
    ----------
    s : string

    Returns
    -------
    float,int,str,bool : type
        Depending on what it can be cast to

    """    
    try:                
        f = float(s)        
        if "." not in s:
            return int
        return float
    except ValueError:
        value = s.upper()
        if value == "TRUE" or value == "FALSE":
            return bool
        return type(s)

Example

str_to_type("true") # bool
str_to_type("6.0") # float
str_to_type("6") # int
str_to_type("6abc") # str
str_to_type(u"6abc") # unicode       

You can capture the type and use it

s = "6.0"
type_ = str_to_type(s) # float
f = type_(s) 
share|improve this answer

RyanN suggests

If you want to return False for a NaN and Inf, change line to x = float(s); return (x == x) and (x - 1 != x). This should return True for all floats except Inf and NaN

But this doesn't quite work, because for sufficiently large floats, x-1 == x returns true. For example, 2.0**54 - 1 == 2.0**54

share|improve this answer

You can generalize the exception technique in a useful way by returning more useful values than True and False. For example this function puts quotes round strings but leaves numbers alone. Which is just what I needed for a quick and dirty filter to make some variable definitions for R.

import sys

def fix_quotes(s):
    try:
        float(s)
        return s
    except ValueError:
        return '"{0}"'.format(s)

for line in sys.stdin:
    input = line.split()
    print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'
share|improve this answer

how about this:

'3.14'.replace('.','',1).isdigit()

which will return true only if there is one or no '.' in the string of digits.

'3.14.5'.replace('.','',1).isdigit()

will return false

edit: just saw another comment ... adding a .replace(badstuff,'',maxnum_badstuff) for other cases can be done. if you are passing salt and not arbitrary condiments (ref:xkcd#974) this will do fine :P

share|improve this answer
3  
This doesn't however account for negative numbers. – Michael Barton Oct 23 '14 at 21:33
    
Or hexadecimal. – twasbrillig Oct 25 '14 at 18:10
9  
Now that is ugly and clunky – Jivan Apr 20 '16 at 12:44
1  
Or numbers with exponents like 1.234e56 (which might also be written as +1.234E+56 and several more variants). – Alfe Apr 22 '16 at 9:29
    
re.match(r'^[+-]*(0[xbo])?[0-9A-Fa-f]*\.?[0-9A-Fa-f]*(E[+-]*‌​[0-9A-Fa-f]+)$', 'str') should do a better job of determining a number (but not all, I'm not claiming that). I don't recommend using this, far better to use the Questioner's original code. – Baldrickk Feb 9 '17 at 15:31

You can use Unicode strings, they have a method to do just what you want:

>>> s = u"345"
>>> s.isnumeric()
True

Or:

>>> s = "345"
>>> u = unicode(s)
>>> u.isnumeric()
True

http://www.tutorialspoint.com/python/string_isnumeric.htm

http://docs.python.org/2/howto/unicode.html

share|improve this answer
2  
Ahh!!!! Forget it, it only checks if all the characters are numbers. Sorry. – Blackzafiro Mar 4 '13 at 16:33
    
how about float? – alvas Mar 23 '13 at 7:55
1  
for non-negative ints it is ok ;-) – andi Mar 22 '14 at 13:10
1  
s.isdecimal() checks if s string is a non-negative integer. s.isnumeric() includes characters that int() rejects. – jfs Oct 19 '14 at 5:29
    
Why does it have to be unicode? – Solomon Ucko May 4 '16 at 23:31

I wanted to see which method is fastest, and turns out catching an exception is the fastest.

import time
import re

check_regexp = re.compile("^\d*\.?\d*$")

check_replace = lambda x: x.replace('.','',1).isdigit()

numbers = [str(float(x) / 100) for x in xrange(10000000)]

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

start = time.time()
b = [is_number(x) for x in numbers]
print time.time() - start # returns 4.10500001907

start = time.time()
b = [check_regexp.match(x) for x in numbers] 
print time.time() - start # returns 5.41799998283

start = time.time()
b = [check_replace(x) for x in numbers] 
print time.time() - start # returns 4.5110001564
share|improve this answer
9  
You should also test performance for invalid cases. No exception is raised with these numbers, which is exactly the "slow" part. – Ugo Méda Jan 28 '13 at 14:17

So to put it all together, checking for Nan, infinity and complex numbers (it would seem they are specified with j, not i, i.e. 1+2j) it results in:

def is_number(s):
    try:
        n=str(float(s))
        if n == "nan" or n=="inf" or n=="-inf" : return False
    except ValueError:
        try:
            complex(s) # for complex
        except ValueError:
            return False
    return True
share|improve this answer
    
I'd like comments on downvotes if possible, thanks. – a1an Oct 1 '13 at 12:58

Just Mimic C#

In C# there are two different functions that handle parsing of scalar values:

  • Float.Parse()
  • Float.TryParse()

float.parse():

def parse(string):
    try:
        return float(string)
    except Exception:
        throw TypeError

Note: If you're wondering why I changed the exception to a TypeError, here's the documentation.

float.try_parse():

def try_parse(string, fail=None):
    try:
        return float(string)
    except Exception:
        return fail;

Note: You don't want to return the boolean 'False' because that's still a value type. None is better because it indicates failure. Of course, if you want something different you can change the fail parameter to whatever you want.

To extend float to include the 'parse()' and 'try_parse()' you'll need to monkeypatch the 'float' class to add these methods.

If you want respect pre-existing functions the code should be something like:

def monkey_patch():
    if(!hasattr(float, 'parse')):
        float.parse = parse
    if(!hasattr(float, 'try_parse')):
        float.try_parse = try_parse

SideNote: I personally prefer to call it Monkey Punching because it feels like I'm abusing the language when I do this but YMMV.

Usage:

float.parse('giggity') // throws TypeException
float.parse('54.3') // returns the scalar value 54.3
float.tryParse('twank') // returns None
float.tryParse('32.2') // returns the scalar value 32.2

And the great Sage Pythonas said to the Holy See Sharpisus, "Anything you can do I can do better; I can do anything better than you."

share|improve this answer
    
I have been coding in mostly JS lately and didn't actually test this so there may be some minor errors. If you see any, feel free to correct my mistakes. – Evan Plaice Feb 18 '12 at 1:37
    
To add support for complex numbers see the answer by @Matthew Wilcoxson. stackoverflow.com/a/3335060/290340. – Evan Plaice Feb 18 '12 at 1:47
    
Using ! instead of not might be a minor error, but you definitely can't assign attributes to the built-in float in CPython. – BlackJack Aug 28 '16 at 11:34

I did some speed test. Lets say that if the string is likely to be a number the try/except strategy is the fastest possible.If the string is not likely to be a number and you are interested in Integer check, it worths to do some test (isdigit plus heading '-'). If you are interested to check float number, you have to use the try/except code whitout escape.

share|improve this answer
4  
Mind posting the results? – Daniel Goldberg Oct 13 '10 at 21:57

There is one exception that you may want to take into account: the string 'NaN'

If you want is_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):

>>> float('NaN')
nan

Otherwise, I should actually thank you for the piece of code I now use extensively. :)

G.

share|improve this answer
2  
Actually, NaN might be a good value to return (rather than False) if the text passed is not in fact a representation of a number. Checking for it is kind of a pain (Python's float type really needs a method for it) but you can use it in calculations without producing an error, and only need to check the result. – kindall Jun 10 '11 at 17:50
6  
Another exception is the string 'inf'. Either inf or NaN can also be prefixed with a + or - and still be accepted. – agf May 22 '12 at 23:10
3  
If you want to return False for a NaN and Inf, change line to x = float(s); return (x == x) and (x - 1 != x). This should return True for all floats except Inf and NaN – RyanN Mar 15 '13 at 20:29
3  
x-1 == x is true for large floats smaller than inf. From Python 3.2 you can use math.isfinite to test for numbers that are neither NaN nor infinite, or check both math.isnan and math.isinf prior to that. – Steve Jessop Jan 22 '14 at 18:39

Here's my simple way of doing it. Let's say that I'm looping through some strings and I want to add them to an array if they turn out to be numbers.

try:
    myvar.append( float(string_to_check) )
except:
    continue

Replace the myvar.apppend with whatever operation you want to do with the string if it turns out to be a number. The idea is to try to use a float() operation and use the returned error to determine whether or not the string is a number.

share|improve this answer
    
You should move the append part of that function into an else statement to avoid accidentally triggering the exception should there be something wrong with the array. – DarwinSurvivor Jul 24 '13 at 5:39

Which, not only is ugly and slow, seems clunky.

It may take some getting used to, but this is the pythonic way of doing it. As has been already pointed out, the alternatives are worse. But there is one other advantage of doing things this way: polymorphism.

The central idea behind duck typing is that "if it walks and talks like a duck, then it's a duck." What if you decide that you need to subclass string so that you can change how you determine if something can be converted into a float? Or what if you decide to test some other object entirely? You can do these things without having to change the above code.

Other languages solve these problems by using interfaces. I'll save the analysis of which solution is better for another thread. The point, though, is that python is decidedly on the duck typing side of the equation, and you're probably going to have to get used to syntax like this if you plan on doing much programming in Python (but that doesn't mean you have to like it of course).

One other thing you might want to take into consideration: Python is pretty fast in throwing and catching exceptions compared to a lot of other languages (30x faster than .Net for instance). Heck, the language itself even throws exceptions to communicate non-exceptional, normal program conditions (every time you use a for loop). Thus, I wouldn't worry too much about the performance aspects of this code until you notice a significant problem.

share|improve this answer
1  
Another common place where Python uses exceptions for basic functions is in hasattr() which is just a getattr() call wrapped in a try/except. Still, exception handling is slower than normal flow control, so using it for something that is going to be true most of the time can result in a performance penalty. – kindall Jun 10 '11 at 17:50
    
It seems that if you want a one-liner, you're SOL – Basic Mar 10 '14 at 11:21
    
Also pythonic is the idea that it's "better to ask forgiveness than permission", regarding the impact of having cheap exceptions. – heltonbiker Apr 26 '16 at 1:20

Your code looks fine to me.

Perhaps you think the code is "clunky" because of using exceptions? Note that Python programmers tend to use exceptions liberally when it improves code readability, thanks to its low performance penalty.

share|improve this answer

If you want to know if the entire string can be represented as a number you'll want to use a regexp (or maybe convert the float back to a string and compare it to the source string, but I'm guessing that's not very fast).

share|improve this answer

Casting to float and catching ValueError is probably the fastest way, since float() is specifically meant for just that. Anything else that requires string parsing (regex, etc) will likely be slower due to the fact that it's not tuned for this operation. My $0.02.

share|improve this answer
9  
Your "2e-2" dollars are a float too (an additional argument for using float :) – tzot Dec 9 '08 at 22:59
6  
@tzot NEVER use a float to represent a monetary value. – Luke Nov 7 '12 at 15:25
4  
@Luke: I totally agree with you, although I never suggested using floats to represent monetary values; I just said that monetary values can be represented as floats :) – tzot Nov 8 '12 at 11:19

protected by Jim Fasarakis Hilliard Oct 1 '16 at 12:47

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.