Skip to content

Instantly share code, notes, and snippets.

@cluelessperson
Last active May 30, 2019 00:51
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 cluelessperson/27e2e41cbc4cbd138feb9dec27d452fb to your computer and use it in GitHub Desktop.
Save cluelessperson/27e2e41cbc4cbd138feb9dec27d452fb to your computer and use it in GitHub Desktop.
def coerce_number(s, zero_if_fail=False):
s = s.strip()
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
if zero_if_fail:
return 0
else:
raise ValueError
print(coerce_number("10"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment