Skip to content

Instantly share code, notes, and snippets.

@pschwede
Last active August 29, 2015 14:16
Show Gist options
  • Save pschwede/8d0f9d5f632c2f1fae17 to your computer and use it in GitHub Desktop.
Save pschwede/8d0f9d5f632c2f1fae17 to your computer and use it in GitHub Desktop.
Convert strings to the value they represent. Written in Python. Can anyone do faster?
def to_value(string):
"""Converts a string to the value it represents.
If a non-string has been given, it stays as it is.
Examples:
>>> to_value("foobar")
"foobar"
>>> to_value(12345)
12345
>>> to_value("12345")
12345
>>> to_value("3.1415")
3.1415
>>> to_value("1,2,1")
[1, 2, 1]
>>> to_value("1,a,.5")
[1, "a", 0.5]
"""
# try if converting int/float back to str looks equal to the original
# string. Return the string otherwise.
for type_ in [int, float]:
try:
return type_(string)
except ValueError:
continue
# if there is a comma, it must be a list
try:
if "," in string:
return [to_value(s) for s in string.split(",") if s]
except AttributeError:
# It's not splittable. Not a string.
return string
except TypeError:
# It's not iterable. Unknown type.
return string
# Getting here means the string couldn't be converted to something else.
# We will return a string then.
return string
@pschwede
Copy link
Author

I just learned about:

from ast import literal_eval as to_value

Or to do exactly the same as the gist (and more):

from ast import literal_eval

def to_value(string):
    try:
        return literal_eval(string)
    except SyntaxError:
        return string
    except ValueError:
        return "'%s'" % string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment