Select Page

How to Convert a String to an Int in Python

by | Programming, Python, Tips

How to Convert a String to Int in Python:

To convert a string to an integer in Python, you need to use the built-in int() function. The int() takes two parameters: the string you want to convert and the base of the number. The default value of the base is 10.

How to Convert an Int to a String in Python:

To convert an integer to a string in Python, you need to use the str() function. This function takes three parameters, the first parameter is the object you want to convert into a string, it can be any object. The second parameter is the encoding of the object, the default is UTF-8. The third parameter is the error response when decoding fails, this defaults to ‘strict’.


Python has data types that we can use to represent different data types. We can use Python strings to represent text-based data and integers to represent whole numbers. We may want to convert a Python string to an integer or vice versa. Python provides built-in methods to perform these conversions: int() and str().

This tutorial will go through how to use the int() method to convert a string to an integer and the str() method to convert an integer to a string.

Python Data Types

The data you are working with will determine how Python stores the data, for example, if you are working with text, Python will store the data as a string. If you read a binary file, the data will be byte-like.

Data types are important because each data types have different properties and operations we can perform on them. For example, you can concatenate strings, but you cannot concatenate strings with integers. If you try to concatenate a string with an integer you will raise the TypeError: can only concatenate str (not “int”) to str. Another example is you can perform mathematical operations on numerical values as floats and integers but if you try to perform mathematical operations with a combination of a string and an integer like division or subtraction, you will raise the TypeError: unsupported operand type(s) for: ‘int’ and ‘str’.

Python String

We define Python strings with single or double quotes. Let’s look at an example of a string:

example_string = "this is an example string."

print(type(example_string)
≺ class 'str' ≻

Python Integer

The Python integer is a non-fractional number like 1, 4, 5, -1, and -50. It is one of the three types of numbers Python supports natively, the others being floating-point and complex numbers. Let’s look at an example of an integer, floating-point and a complex number in Python:

an_integer = 10
a_float = 3.14
a_complex_number = 4j 

print(type(an_integer))

print(type(a_float))

print(type(a_complex_number))
≺class 'int'≻
≺class 'float'≻
≺class 'complex'≻

Converting the data type of a variable from one type to another is called typecasting. If you want to convert a string to an integer or an integer to a string you have to use one of the built-in methods for typecasting.

Convert String to Int in Python

In Python, we use the int() method to convert a string to an integer value. The int() method takes two parameters: the value to convert into an integer and the base you want your data in. The second parameter is optional. Let’s look at the syntax in code form:

int(value, base)

The value can be a number or a string that we can convert to an integer. Let’s look at an example of using the int() method to convert a string to an integer:

value = "10"
print(int(value))

Running the code gives us the following output:

10

Example

Developers commonly the int() function when a value inserted into the program using the input() function needs to be in integer form. The input() function returns a string, for example:

number = input("Enter a number: ")

print(number)

print(type(number))
16
≺class 'str'≻ 

We cannot calculate the square root of a string, therefore we must convert the value to an integer. Let’s look at how we would do that in the code:

number = int(input("Enter a number:  "))
<meta charset="utf-8">
print(number)

print(type(number))

square_root = number ** 0.5

print(square_root)

The above code takes the input, converts it to an integer and then calculates the square root using the exponentiation operator. The program then prints the result to the console. We also print the original value and its type to the console. Let’s run the code to see what happens:

16
≺class 'int'≻
4.0

The program successfully converts the input to an integer and calculates the square root.

Convert Int to String in Python

n Python we use the str() method to convert any object to a string. The syntax of the str() function is

str(object, encoding='UTF-8', errors='strict')

The second and third parameters are optional. The second parameter is the encoding of the object, the default is UTF-8. The third parameter is the error response when decoding fails, this defaults to ‘strict’.

Example

Following on from the above program, we may want to print the number and its square root in a message with a string. To print multiple values we need to use the concatenation operator +. The code would look like this:

print("The square root of " + number + "is " + square_root)

However, if we run the code we will get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
1 print("The square root of " + number + "is " + square_root)

TypeError: can only concatenate str (not "int") to str

This error occurs because you cannot concatenate a string to an integer or a float. To fix the code we need to convert both numerical values to strings using the str() method. Let’s look at the revised code:

print("The square root of " + str(number) + " is " + str(square_root))

Let’s run the code to see what happens:

The square root of 16 is 4.0

The code successfully prints the complete string to the console because we converted the two numerical values to strings.

Convert List of String to List of Integers in Python

We may come across a list of numerical strings that we want to convert to a list of integers. For example, we might have a list of the number of apples sold per day for a week and we want to calculate the sum of apples sold for the entire week. We cannot use the sum() function on strings, so we can use a list comprehension that converts every value in the list to an integer. Then we can calculate the sum by passing the list of integers to the sum() function. Let’s look at how this would look in code:

apples_sold = ["24", "10", "50", "90", "4", "12", "8"]

apples_sold_values = [int(apple) for apple in apples_sold]

print(apples_sold_values)

print(sum(apples_sold_values))

Let’s run the code to see what happens:

[24, 10, 50, 90, 4, 12, 8]
198

The program successfully converts the list of strings to a list of integers and calculates the sum of the apples sold over a week.

Summary

Congratulations on reading to the end of this tutorial! You can use the int() method to convert a string to an integer in Python. This method is useful if you need to store a numerical string as an integer to perform mathematical operations. You can use the str() method to convert an integer to a string. An important use case of the str() method is to convert numerical values to numerical strings to concatenate with other strings.

For further reading on string manipulation, go to the article: How to Solve Python TypeError: not enough arguments for format string.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!