0

I have strings like:

"Some Test"
"00000.sds*Som'e 'Test'01/234232"
"Some Test'01/234232"
"14"
"12.523232"
"-12.523232"

What is the best way (with some function) in Python to be able to check the content of a string to determine whether it can be casted to a "float(stringvalue)", or if it has to remain a string? The resulting output needs to be:

"Some Test"
"Some Test'01/234232"
"00000.sds*Som'e 'Test'01/234232"
14
12.523232
-12.523232
AndyG
  • 39,700
  • 8
  • 109
  • 143
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 2
    http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python – C.B. Jan 22 '14 at 18:28

1 Answers1

2

The preferred way is to try to perform the cast and catch the ValueError:

def cast(numeric_string):
    try:
        return float(numeric_string)
    except ValueError:
        return numeric_string

The problem here is that you don't really know if it worked or not. To avoid having to check the type, you could return a 2-tuple with the success result as well:

def try_cast(numeric_string):
    try:
        return True, float(numeric_string)
    else:
        return False, numeric_string

Then, to use, you can do:

did_cast, value = try_cast(my_string)
if did_cast:
     # treat value as a number
else:
     # treat value as a string
John Spong
  • 1,361
  • 7
  • 8