Created
March 6, 2026 01:22
-
-
Save yeiichi/f2c80c9969eaf98ea0cf8613ee15dceb to your computer and use it in GitHub Desktop.
Parse a numeric string into int or float
This file contains hidden or 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 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