Related Articles

# 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

 `# Initialising a string ``# with decimal value``string ``=` `"100"`` ` `# Show the Data type``print``(``type``(string))`` ` `# Converting string into int``string_to_int ``=` `int``(string)`` ` `# Show the Data type``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

 `# Initialising a string``# with hexadecimal value``string ``=` `"0x12F"`` ` `# Show the Data type``print``(``type``(string))`` ` `# Converting hexadecimal ``# string into int``string_to_int ``=` `int``(string, ``                    ``base``=``16``)``# Show the Data type``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

 `# User-defined function to ``# convert a string into integer``def` `string_to_int(input_string):``   ` `  ``output_int ``=` `0``   ` `  ``# Check if the number contains``  ``# any minus sign or not, ``  ``# i.e. is it a negative number or not. ``  ``# If it contains in the first``  ``# position in a minus sign,``  ``# we start our conversion ``  ``# from the second position which``  ``# contains numbers.``  ``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)):``     ` `    ``# calculate the place value for ``    ``# the respective digit``    ``place_value ``=` `10``*``*``(``len``(input_string) ``-` `(i``+``1``))``     ` `    ``# calculate digit value``    ``# ord() function gives Ascii value``    ``digit_value ``=` `ord``(input_string[i]) ``-` `ord``(``'0'``)``     ` `    ``# calculating the final integer value``    ``output_int ``+``=` `place_value ``*` `digit_value``     ` `  ``# if check_negative is true ``  ``# then final integer value ``  ``# is multiplied by -1``  ``if` `check_negative :``    ``return` `-``1` `*` `output_int``  ``else``:``    ``return` `output_int`` ` `# Driver code``if` `__name__ ``=``=` `"__main__"` `: ``   ` `  ``string ``=` `"554"`` ` `  ``# function call``  ``x ``=` `string_to_int(string)`` ` `  ``# Show the Data type``  ``print``(``type``(x))`` ` `  ``string ``=` `"123"`` ` `  ``# Show the Data type``  ``print``(``type``(string_to_int(string))) `` ` `  ``string ``=` `"-123"`` ` `  ``# Show the Data type``  ``print``(``type``(string_to_int(string)))`

Output:

```<class 'int'>
<class 'int'>
<class 'int'>
```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up