Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python: Trys to cast a string into int or float if possible, won't throw an error if not, just returns the string untouched.
# trys to cast strings into float or int if possible, or returns it.
def castToType(n):
n = n.replace(",", ".")
num = float(n)
if "." not in n:
return int(num)
return num
except ValueError:
return n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment