How to convert string to integer in Python?
Last Updated :
10 Jul, 2020
In Python, a string can be converted into an integer using the following methods :
Method 1: Using built-in int() function:
If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer.
Syntax : int(string, base)
Parameter : This function take following parameters :
- string : consists of 1’s, 0’s or hexadecimal ,octal digits etc.
- base : (integer value) base of the number.
Returns : Returns an integer value, which is equivalent
of string in the given base.
Code :
Python3
string = "100"
print ( type (string))
string_to_int = int (string)
print ( type (string_to_int))
|
Output:
<class 'str'>
<class 'int'>
By default, int() expect that the string argument represents a decimal integer. Assuming, in any case, you pass a hexadecimal string to int(), then it will show ValueError. In such cases, you can specify the base of the number in the string.
Code:
Python3
string = "0x12F"
print ( type (string))
string_to_int = int (string,
base = 16 )
print ( type (string_to_int))
|
Output:
<class 'str'>
<class 'int'>
Method 2: Using user-defined function:
We can also convert a string into an int by creating our own user-defined function.
Approach:
- we’ll check, if the number has any “-” sign or not, for if it is a negative number it will contain “-” sign. If it contains “-” sign, then we will start our conversion from the second position which contains numbers.
- Any number, suppose 321, can be written in the structure : 10**2 * 3 + 10**1*2 + 10**0*1
- Similarly, we split each of the input number using ord(argument), ord(‘0’) will return 48, ord(‘1’) returns 49 and so forth.
- The logic here is that ord(‘1’) – ord(‘0) = 1, ord(‘2’) – ord(‘0’) = 2 and so on which gives us the significant number to be fetched from the given input number.
- Finally, the result we get from the function is an Integral number which we changed over from the given string.
Code:
Python3
def string_to_int(input_string):
output_int = 0
if input_string[ 0 ] = = '-' :
starting_idx = 1
check_negative = True
else :
starting_idx = 0
check_negative = False
for i in range (starting_idx, len (input_string)):
place_value = 10 * * ( len (input_string) - (i + 1 ))
digit_value = ord (input_string[i]) - ord ( '0' )
output_int + = place_value * digit_value
if check_negative :
return - 1 * output_int
else :
return output_int
if __name__ = = "__main__" :
string = "554"
x = string_to_int(string)
print ( type (x))
string = "123"
print ( type (string_to_int(string)))
string = "-123"
print ( type (string_to_int(string)))
|
Output:
<class 'int'>
<class 'int'>
<class 'int'>
Please Login to comment...