Converting String to int
Converting a Python string to an int. If you have a decimal integer represented as a string, and you want to convert the Python string to an int, then you can just pass the string to
int(), which returns a decimal integer.
You can see the variable
s has been defined as the string
"110". Returning that shows that it’s a string with the quotes. And if we want the integer version of that, we can see that that’s returned as an integer without any quotes around it.
We can check the type of that output using
type(). As you can see, it’s of
<class 'int'>. By default,
int() assumes that the string argument represents a decimal integer.
00:52 If you pass the wrong kind of data to it, this can lead to some confusion if you’ve not been fully aware of the types of numbers you’re passing to it.
As you can see, trying to pass it a hexadecimal number here has generated a
ValueError. The error message says the string is not a valid decimal integer.
It’s important to recognize the difference between two types of failed results of passing a string to
int(). Firstly, let’s look at a logical error where
int() does know how to parse the string, but not in the way we expected.
Here’s a string that’s intended to be binary, but
int() will misinterpret it. In this example, the intended result was 210, the decimal representation of that binary string.
Unfortunately because that behavior wasn’t specified
int() will assume the string was a decimal integer and produce the results seen on screen.
01:54 A good safeguard for this behavior is to always define any string representation using explicit bases.
However, passing our new binary string to
int() leaves the
ValueError we saw before. If you pass a string to
int() which is not in decimal, you can specify the number using the “base” argument as seen here.
Finally, the correct result is obtained.
int() has understood you’re passing a binary string and expecting a decimal integer. Note that the value for the base argument is not limited to 2, 8, 10, and 16, the number of bases we’ve seen so far, but can be any arbitrary number.
02:47 Now that you’re comfortable with the ins and outs of converting Python strings to ints you’ll learn how to do the inverse operation in the next section.
Become a Member to join the conversation.
javierortin on May 19, 2020
Would be nice if the tutorial went deeper and added signed integers. That’d be useful.