Last active
August 16, 2020 16:14
-
-
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.
This file contains 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 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