Number Parsing in Python
Our first example demonstrates parsing numbers from strings, which is a common task in many programs. Here’s how to do it in Python:
# Python's built-in functions handle number parsing
def main():
# Parse a float
f = float("1.234")
print(f)
# Parse an integer
i = int("123")
print(i)
# Parse a hexadecimal number
d = int("0x1c8", 16)
print(d)
# Parse an unsigned integer (same as int in Python)
u = int("789")
print(u)
# Parse a base-10 integer (same as int)
k = int("135")
print(k)
# Parsing functions raise an exception on bad input
try:
int("wat")
except ValueError as e:
print(e)
if __name__ == "__main__":
main()Let’s break down the key points:
Python’s built-in
float()function is used to parse floating-point numbers from strings.The
int()function is used to parse integers. It can handle different bases:- By default, it parses base-10 integers.
- To parse hexadecimal numbers, we pass the base as the second argument:
int("0x1c8", 16).
Python doesn’t have separate types for signed and unsigned integers, so we use
int()for both cases.There’s no direct equivalent to Go’s
Atoi()function in Python, butint()serves the same purpose for base-10 integers.When parsing fails, Python raises a
ValueErrorexception, which we can catch and handle.
Here’s what you’d see if you run this program:
$ python number_parsing.py
1.234
123
456
789
135
invalid literal for int() with base 10: 'wat'This example demonstrates how Python handles number parsing, which is generally simpler and more straightforward compared to some other languages, as it relies on built-in functions and doesn’t require importing additional modules for basic parsing tasks.
Next, we’ll look at another common parsing task: URLs.