Skip to content

Instantly share code, notes, and snippets.

@HubTou
Last active January 21, 2023 13:49
Show Gist options
  • Save HubTou/c39039dc4cf59d94d061a1fdc03a6d3f to your computer and use it in GitHub Desktop.
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
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