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.
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.
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.
Become a Member to join the conversation.