Python - How To Convert String to Integer in Python

ID : 49

viewed : 128

Tags : PythonPython StringPython Integer

vote vote

97

A string in Python is a sequence of Unicode characters. The integers are the positive or negative whole numbers. In Python, integers can be of unlimited size and are only constrained by the system’s memory.

In this tutorial, we will introduce how to convert a string to an integer in Python.

Use the int() Function to Convert a String to an Integer in Python

The built-in int() function in Python converts a string to its corresponding integer value. This function can take any Python data type as its parameter and return the corresponding integer value, as long as it is definable.

For example,

A = "56" B = "40" print(int(A)+4) print(int(A)+int(B)) 

Output:

60 96 

The int() function converts string A into its integer value of 56 and returns the final output of 60 after adding 4 to it. Similarly, the string B is converted into its integer value of 40. The final output is printed after the integer values of A and B are added.

Use the List Comprehension Method to Convert a String to an Integer in Python

List comprehension is a simple, clean way to create lists using loops in a single line of code. We can use it to convert strings in iterables to an integer.

We will use the map() function to apply the int() function on elements of the given iterable.

For example,

A = (('90','88'),('78','56'),('2','4','6')) B = [list(map(int, x)) for x in A] print(B) 

Output:

[[90, 88], [78, 56], [2, 4, 6]] 

Similarly, we can adjust the code based on the iterable encountered.

Create a User-Defined Function to Convert a String to an Integer in Python

We can create a function string_to_int(), which takes a string as a parameter and returns the corresponding integer value.

This method uses the int() function to perform the conversion elegantly. We will put the code in a try and except block to handle exceptions raised while making the required conversions.

For example,

def string_to_int(s):     try:         temp = int(eval(str(s)))         if type(temp) == int:             return temp     except:         return      val = string_to_int('10') print(val) 

Output:

10 

  • Related HOW TO?