Last active
January 21, 2023 13:49
-
-
Save HubTou/c39039dc4cf59d94d061a1fdc03a6d3f to your computer and use it in GitHub Desktop.
A little Python function to deal with values of other types contained in strings, for example, for sorting purposes
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
import dateutil.parser | |
def get_string_type_and_value(string): | |
""" Return the type and value of the string parameter's content """ | |
# int? | |
try: | |
value = int(string) | |
return "int", value | |
except ValueError: | |
pass | |
# float? (with point decimal separator) | |
try: | |
value = float(string) | |
return "float", value | |
except ValueError: | |
pass | |
# float? (with comma decimal separator) | |
try: | |
value = float(string.replace(".", ",")) | |
return "float", value | |
except ValueError: | |
pass | |
# complex? (Python's format, for example "1+2j") | |
try: | |
value = complex(string) | |
return "complex", value | |
except ValueError: | |
pass | |
# datetime? | |
try: | |
value = dateutil.parser.parse(string) | |
return "datetime", value | |
except dateutil.parser._parser.ParserError: | |
pass | |
# str! | |
return "str", string |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment