Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Created March 6, 2026 01:22
Show Gist options
  • Select an option

  • Save yeiichi/f2c80c9969eaf98ea0cf8613ee15dceb to your computer and use it in GitHub Desktop.

Select an option

Save yeiichi/f2c80c9969eaf98ea0cf8613ee15dceb to your computer and use it in GitHub Desktop.
Parse a numeric string into int or float
def parse_number(x: int | float | str | None):
"""Parse a numeric string into int or float.
Return None for empty or common null markers; leave non-string inputs unchanged.
"""
if not isinstance(x, str):
return x
s = x.strip().replace(",", "")
if not s or s.lower() in {"na", "n/a", "null", "none"}:
return None
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment