Last active
August 29, 2015 14:16
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I just learned about:
Or to do exactly the same as the gist (and more):