How to Convert String Into Integer in Python?

In Python, the string is defined as any sequence containing the alphabet, numbers, characters, etc. The integer is defined as a whole number, either positive or negative. For all mathematical calculations, the integer and float values are used in Python, so to convert the numeric string into an integer, the inbuilt “int()” function is used in Python.

This write-up will enable you to convert strings into an int in Python. The following terms are discussed in depth with numerous examples:

All right, let’s get started!

How to Convert String Into Integer in Python?

In Python, the string is converted into an integer value using the built-in “int()” function. The “int()” function takes only numeric strings data type as an argument and returns an error if the non-string data type is passed.

Example 1: Simple Conversion Using int() Function

In the following example, the “int()” function is utilized to convert the string value into an integer value.

Code:

String_value = '90'
print('String Value: ', String_value)
print('\nData Type of String Value: ', type(String_value))

# using int() function
Integer_value = int(String_value)
print('\nInteger Value: ', Integer_value)
print('\nData Type of integer Value: ', type(Integer_value))

#adding integer value to another integer
print('\nAddition of integer value: ', Integer_value + 20)

In the above code:

  • The string value containing number is initialized.
  • The “int()” function accepts the input string variable as an argument and retrieves the integer.
  • The “type()” function is used before and after the conversion of the string to an integer to verify the data type.
  • A mathematical operation, “addition”, is performed on the converted value.

Output:

In the above output, the string value has been converted into an integer value.

Example 2: Advanced Conversion Using int() Function

In the example given below, the “int()” function is used to convert a string into an integer during the execution of the algebraic expression.

Code:

first_string = '14'
second_string = '10'
subtraction = int(first_string) - int(second_string)
print('Difference of Numbers: ', subtraction)

In the above code:

  • Two string values containing numbers are initialized in the program.
  • The “int()” function is used along with the algebraic expression to convert the input string into an integer and perform calculations.

Output:

The string value has been converted into an integer value, and the respective mathematical operation has been performed on the converted values.

Here’s the end of this Python guide!

Conclusion

To convert the input string into an integer, the inbuilt “int()” function is utilized in Python script. The “int()” function returns “TypeErrors” while executing non-string or non-integer data types. This write-up presented all the necessary details related to the strings into integers conversion in Python.