To convert a string variable to an integer in Python, use the int() function.

x = "1"
y = int(x)

print(y)

#Output:
1

When working with string variables in Python, the ability to easily be able to use and change these variables is valuable.

One such situation is if you want to create an integer from a string variable.

To convert a string variable to an integer in Python, use the int() function.

int() takes a string variable which represents an integer, such as “12” or “4”, and returns an integer variable.

Below shows a few simple examples of how you can use int() to convert a string to an integer in Python.

a = "1"
b = "12"
c = "43"

print(int(a))
print(int(b))
print(int(c))

#Output:
1
12
43

Using int() to Convert String to Integer in Python

To use int(), there are a few things you should know. First, you need to pass a string literal representing an integer.

For example, if you try to pass a string which has letters, then you will get a ValueError.

You will also get a ValueError if you pass a string which representing a numeric value that is a floating-point number. If you want to convert a string to a float in Python, then use float().

Below shows a few more examples of how to use int() and shows some common errors which might come from the use of int().

a = "1"
b = "1.23"
c = "abc"

print(int(a))
print(int(b))
print(int(c))

#Output:
1
ValueError: invalid literal for int() with base 10: '1.23'
ValueError: invalid literal for int() with base 10: 'abc'

Hopefully this article has been useful for you to learn how to convert a string to integer with Python.

Categorized in:

Python,

Last Update: March 11, 2024