Reputation: 1899
I need some way to reliably identify whether a string can be of another type eg. "1"
would evaluate to 1
- an int, "2.0"
would evaluate to 2.0
- a float and "John has 3 apples" would just evaluate to a string. Is there some package that does this - builtin or otherwise?
It would be great if it also worked on dates and currency
Upvotes: 1
Views: 636
Reputation: 799
You can do this with ast.literal_eval
int_type = ast.literal_eval("1")
float_type = ast.literal_eval("2.0")
But will only work on python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, None and Ellipsis
Upvotes: 3
Reputation: 2917
You can use try/except
block for primitive types:
strings = ["1", "2.0", "John has 3 apples"]
def get_value(s):
types = (int, float, str)
for type in types:
try:
return type(s)
except ValueError:
pass
print(get_value(strings[0]))
print(get_value(strings[1]))
print(get_value(strings[2]))
Upvotes: 3