In this tutorial, we will learn how to convert Python String to Int and vice-versa (Python Int to String). We will also explore the how-to convert String into an int with different bases and the possible conversion errors.
Python String to Int Conversion
It is crucial for a developer to know the different Python Data types and conversions between them. Let’s take Python String to Int conversion itself, whenever we get the input from the user we typically use the input() function
The input() function reads a data entered by the user and converts it into a string and returns it. Even though the user has entered a numeric value, it will be automatically converted to String by Python, which cannot be used directly for any manipulation.
For example, if we want to divide the number entered by the user by 2.
>>> num = input("Enter a number : ") Enter a number : 10 >>> num '10'
The value stored inside num is not an integer 10 but the string ’10’. Let’s check the type of num for a confirmation.
>>> type(num) <class 'str'>
If we try to divide the num by 2, we will get an Unsupported operand type error.
>>> print( num /2) Traceback (most recent call last): File "<pyshell#4>", line 1, in print( num /2) TypeError: unsupported operand type(s) for /: 'str' and 'int'
We cannot perform division operation on a String. So we need to perform the type conversion into the corresponding data type. Let’s limit it to int for now.
Using int() function to convert Python String to Int
For integer related operation, Python provides us with int class. We can use the int() function present in the int class to convert Python String to Int.
The int() function comes in two flavors
- int(x) – Returns the integer objects constructed from the argument passed, it returns 0 if no argument is passed. It will create an integer object with the default base 10 (decimal).
- int (x, base) – This method also returns the integer object with the corresponding base passed as the argument.
Let’s try to fix the issue which has happened in the above code. All we need to do is to just pass the num variable to the int() function to get it converted to an integer.
>>> num = int(num)
>>> type(num)
<class 'int'>
>>> print(num /2)
5.0
Converting to different Bases
We are able to successfully convert a string to an integer using the int() function, which is of base 10.
Let’s try to convert the String to different bases other than decimal such as binary (base 2), octal (base 8) and hexadecimal (base 16)
>>> val = '1101' >>> base2int = int(val, 2) >>> base2int 13 >>> val = '13' >>> base8int = int(val, 8) >>> base8int 11 >>> val = '1A' >>> base16int = int(val, 16) >>> base16int 26
Optionally we can also pass the String with the prefix for each base.
- ‘0b’or ‘0B’ for binary
- ‘0o’ or ‘0O’ for octal
- ‘0x’ or ‘0X’ for hexadecimal
>>> prefixedVal = '0b110' >>> base2int = int(prefixedVal, 2) >>> base2int 6 >>> prefixedVal = '0o11' >>> base8int = int(prefixedVal, 8) >>> base8int 9 >>> prefixedVal = '0xB' >>> base16int = int(prefixedVal, 16) >>> base16int 11
Conversion Errors
Not all String can be converted into an integer. Below are some of the possible scenarios where int() function will throw an error.
1. Non-Numeric Characters
Whenever there is a non-numeric character in the String. We will get ValueError
>>> val = '15b' >>> val = int(val) Traceback (most recent call last): File "<pyshell#11>", line 1, in val = int(val) ValueError: invalid literal for int() with base 10: '15b'
2. Floating Point String
Similarly, we cannot convert a floating-point string to an integer, and we will get the same ValueError
>>> num = '17.7' >>> num = int(num) Traceback (most recent call last): File "<pyshell#13>", line 1, in num = int(num) ValueError: invalid literal for int() with base 10: '17.7'
3. Comma in Numbers
It is quite common to represent a number with a comma in Math, but the same cannot be applied in the computer world. If a number has a comma in it, then the int() function will throw an error.
>>> commaVal = '12,34,567' >>> val = int(commaVal) Traceback (most recent call last): File "<pyshell#15>", line 1, in val = int(commaVal) ValueError: invalid literal for int() with base 10: '12,34,567'
But, with a simple workaround, we can overcome this issue. We need to replace the comma with a blank before converting to integer
>>> val = int(commaVal.replace(",", ""))
>>> val
1234567
4. Invalid ranges
There is a specific allowed range for each base,
- Binary (base 2) can have only o and 1
- Octal (base 8) can have only values between 0 to 7
- Hexadecimal (base 16) can have only values between 0 to 7 and A to F
We have to adhere to the specified ranges, if not we will get ValueError
>>> val = '123' >>> base2int = int(val, 2) Traceback (most recent call last): File "<pyshell#1>", line 1, in base2int = int(val, 2) ValueError: invalid literal for int() with base 2: '123'
For Binary base only 0 and 1 are allowed, we have used 2,3, and hence we will get ValueError
>>> val = '8' >>> base8int = int(val, 8) Traceback (most recent call last): File "<pyshell#5>", line 1, in base8int = int(val, 8) ValueError: invalid literal for int() with base 8: '8'
Octal allows the range of 0 to 7 Since ‘8’ is not a valid octal range. We are getting the error.
>>> val = 'H' >>> base16int = int(val, 16) Traceback (most recent call last): File "<pyshell#7>", line 1, in base16int = int(val, 16) ValueError: invalid literal for int() with base 16: 'H'
HexaDecimal allows 0 to 7 and A to F, ‘H’ is not a valid range for the base 16.
Python Int to String Conversion
Converting a Python Int to String is pretty straight forward, we just need to pass the integer to the str() function. We don’t have to worry about the type of number or its bases.
>>> num = 13 >>> strNum = str(num) >>> strNum '13' >>> binaryNum = '0b1101' >>> strBinaryNum = str(binaryNum) >>> strBinaryNum '0b1101' >>> hexNum = '0xA12' >>> strHexNum = str(hexNum) >>> strHexNum '0xA12'
Happy Learning!!
Leave a Reply