Skip to content

Instantly share code, notes, and snippets.

@jaquinocode
Last active August 16, 2020 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaquinocode/d7a84db8a1318482bf04ef4f0227472c to your computer and use it in GitHub Desktop.
Save jaquinocode/d7a84db8a1318482bf04ef4f0227472c to your computer and use it in GitHub Desktop.
Checks if a string is an int, float, or string in a way that's dependable & readable.
def int_float_or_string(string):
try:
int(string) # strict and nice
return int
except ValueError:
# float() is too permissive, this is better
return float if is_strictly_float(string) else str
def is_strictly_float(string):
if string.startswith("-"):
string = string[1:]
return "." in string and string.replace(".", "", 1).isdecimal()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment