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:
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
ValueError
exception, which we can catch and handle.
Here’s what you’d see if you run this program:
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.