int()Function to Convert a String to an Integer in Python
- Use the List Comprehension Method to Convert a String to an Integer in Python
- Create a User-Defined Function to Convert a String to an Integer in Python
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.
int() Function to Convert a String to an Integer in Python
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.
A = "56" B = "40" print(int(A)+4) print(int(A)+int(B))
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
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.
A = (('90','88'),('78','56'),('2','4','6')) B = [list(map(int, x)) for x in A] print(B)
[[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
except block to handle exceptions raised while making the required conversions.
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)