Convert Python String to Int: A Step-by-Step Guide - Alps Academy (2024)

Convert Python String to Int: A Step-by-Step Guide - Alps Academy (1)

The process of converting a string to an integer in python is simple, just use the int() function, such as x = int(x) to convert the variable x from a string to an integer as seen here:

x = "3"x = int(x)print(x)print("The string x is now a ", type(x))

Output:
3
The string x is now a <class ‘int’>

The remainder of this article goes into great detail about converting a string into an integer and related matters.

We start with the question of what is a string and what is ‘int’? Int is used in python to represent an integer which, like string, is a data type.

Menu

  1. Strings and Integers are Python Data Types
  2. Python Casting and Data Type Conversion
  3. Examples of String to Int Conversion
  4. Convert String to Int in Python Safely
  5. Alternative Approaches to Convert a String to an Integer
  6. FAQ

1 - Strings and Integers are Data Types in Python

To hold different types of data we use data types.

For example, we have numbers that we may with to use with some calculations, we have numbers used in dates and times, and also numbers used in normal text such as telephone numbers.

Data Types

Numbers include integer and floating point numbers:

  • Integers (int): Whole numbers without any decimal point, like 5, -3, 1000, etc.
  • Floating-point numbers (float): Numbers that have a decimal point or use exponential (scientific) notation, like 3.14, -0.001, 1.45×103, etc.

Text written in sentences such as words are called strings and are created with the use of quotation marks in python:

  • Strings (str): Sequences of characters enclosed within either single quotes (‘) or double quotes (“). For example, “hello”, ‘world’, “123”, etc.

These are called the primitive types in python.

There are other data types like a Boolean (True or False), and when there is more than one value we can use data structures such as lists, sets, tuples and dictionaries.

2 -Python Casting and Data Type Conversion

Converting a data type into a different data type is known as casting, data casting or data type conversion in python. Lets explain out first example

x = "3"x = int(x)print(x)print("The string x is now a ", type(x))

Output:
3
The string x is now a <class ‘int’>

  1. A string variable called x with a value of ‘3’ is created first.
  2. This string is then converted into an integer with a value of 3
  3. The value of x is printed
  4. The type of x is also printed t show that it is a string.
  5. The output shows that, in python, the integer data type is a class, and that class is known as ‘int’

Using the int() Function

If we have a digit that we want to use like a number then we need to make sure it is of the integer data type. If we have a string then the results will not be what we expect.

Let’s see a simple example of the difference when multiplying an age of 21, first incorrectly as a string , then correctly as an integer.

There is no error message, but have a look at the output.

age = "21"print (age*2)age = int(age)print(age*2)

Output:
2121
42

We expect to see the value of 42 for the variable age, which we do when we convert the string into an integer. But what is 2121?

Using the symbol * does multiply integers as you expect, but it also repeats strings the given amount of times. So the two characters of ‘2’ the ‘1’ are repeated to create the new sting of ‘2121’.

3 - Examples of String to Int Conversion

Here are some examples of string to int conversion.

age = "19"days = '14'temp = '-5'cost = "1000"age = int(age)days = int(days)temp = int(temp)cost = int(cost)print(age,days,temp,cost)

Output: 19 14 -5 1000

4 - Convert String to Int in Python Safely

There are different formats of numbers that can result in an error message when a python string convert to an integer is attempted. The suggested approach to deal with issues is to use try and except.

The following code snippets show the tests and results of different forms of the integer 3. In the following strings there are some potential issues that are tested below:

3.0 , 3.2 , -3 , 003

test = "3.0"test = int(test)print(test)print("The string x is now a ", type(test))

Output: ValueError: invalid literal for int() with base 10: ‘3.0’

test = "3.2"test = int(test)print(test)print("The string x is now a ", type(test))

Output: ValueError: invalid literal for int() with base 10: ‘3.2’

test = "-3"test = int(test)print(test)print("The string x is now a ", type(test))

Output: -3
The string x is now a <class ‘int’>

test = "003"test = int(test)print(test)print("The string x is now a ", type(test))

Output: 3
The string x is now a <class ‘int’>

Try and Except

We can see the floats 3.0 and 3.2 are problematic. If we know the string is a number but we don’t know if it is a floating point number or an integer we can do the following:

#solution for a float formattest = '3.0'try: test = int(float(test))except: test = -1print(test)print("The string x is now a ", type(test))

Output: 3
The string x is now a <class ‘int’>

Do you wish to round down numbers? If you do then this code will work as testing with 3.2 resulted in the number being changed to 3 to be an integer.

#solution for a float formattest = '3.2'try: test = int(float(test))except: test = -1print(test)print("The string x is now a ", type(test))

Output: 3
The string x is now a <class ‘int’>

5 - Alternative Approaches to Convert a String to an Integer

There are other approaches with different success rates with our testing (3, 3.0, 3.2, -3, 003). The code will show how a successful convert from string to int can be seen, but we will also put the output for all of the testing.

isdigit()

test = "3"if test.isdigit(): test = int(test) print(test) print("The string x is now a ", type(test)) else:print(test, "is not a valid integer")

Output: 3
The string x is now a <class ‘int’>

Testing the strings 3.0, 3.2, -3 and ‘003’.

Output: 3.0 is not a valid integer

Output: 3.2 is not a valid integer

Output: -3 is not a valid integer

Output: 3
The string x is now a <class ‘int’>

The last example tests the string “003” and does convert correctly. Both floats are correctly identified as not integers and can be dealt with in the else or except options in the code. The major error is with -3, as the results state this is not a valid integer.

isnumeric()

test = "3"if test.isnumeric(): test = int(test) print(test) print("The string x is now a ", type(test)) else:print(test, "is not a valid integer")

Output: 3
The string x is now a <class ‘int’>

Testing the strings 3.0, 3.2, -3 and ‘003’.

Output: 3.0 is not a valid integer

Output: 3.2 is not a valid integer

Output: -3 is not a valid integer

Output: 3
The string x is now a <class ‘int’>

The results for isnumeric() and isdigit() are identical.

isinstance()

test = "3"if isinstance(test,int): test = int(test) print(test) print("The string x is now a ", type(test)) else:print(test, "is not a valid integer")

Output: 3 is not a valid integer

The data type needs to be an integer for isinstance() to return True, so it is not relevant for our purposes.

eval()

test = "3"print(eval(test)+0)print("The string x is now a ", type(test)) 

Output: 3
The string x is now a <class ‘str’>

The data type has not changed from string to int using eval although we were able to apply calculations of the digit as if it was an integer.

test = "3.2"print(eval(test)+1)print("The string x is now a ", type(test)) 

Output: 4.2
The string x is now a <class ‘str’>

In this example to number 3.2 is not an integer but we can add one to it as if it was a floating point number, giving the output of 4.2 (3.2 + 1), yet we still have a string data type.

test = "003"print(eval(test)+1)print("The string x is now a ", type(test)) 

Output: 003
^
SyntaxError: invalid token

The final test using the string “003” resulted in an error.

literal_eval()

The results for literal_eval() show the numbers are converted to either an integer or a float, but it also does not like the string ‘003’.

from ast import literal_evaltest = "3"test = literal_eval(test)print(test)print("The string x is now a ", type(test))

Output: 3
The string x is now a <class ‘int’>

Output: 3.0
The string x is now a <class ‘float’>

Output: 3.2
The string x is now a <class ‘float’>

Output: -3
The string x is now a <class ‘int’>

Output: 003
^
SyntaxError: invalid token

Again we see the final test using the string “003” resulted in an error.

6 - FAQ

There are common questions asked about how to convert a string to an int in python. Here is a range of frequently asked questions with solutions and example python code.

How do you convert a string to an integer in Python?

You can convert a string to an integer in Python using the int() function.

What happens if the string cannot be converted to an integer?

If the string cannot be converted to an integer then a ValueError will occur. Use try and except to catch errors.

Can you convert a string with a different base to an integer?

Yes, you can convert a string with a different base to an integer by using the int().

return to the top menu

Convert Python String to Int: A Step-by-Step Guide - Alps Academy (2024)
Top Articles
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 5237

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.