Track
Data type errors are one of the most common obstacles in Python, especially for beginners. A common data type error happens when numbers are formatted as strings, leading to miscalculations, incorrect insights, or flat-out error messages.
In this tutorial, I’ll show you how to navigate these errors, and how to convert Python strings to integers.
The Quick Answer: How to Convert a Python String to an Integer
If your string represents a whole number (i.e., 12
), use the int()
function to convert a string into an integer. If your string represents a decimal number (i.e., 12.5
), use the float()
function to convert a string into a float. You can find examples below:
# Converting a string into an integer
number_str = "10"
number_int = int(number_str)
print(number_int) # Output: 10
# Converting a string into a float
decimal_str = "10.5"
decimal_float = float(decimal_str)
print(decimal_float) # Output: 10.5
Data Types in Python
Python is a dynamically typed language, featuring a variety of data types from strings and integers to floating-point numbers and booleans. Understanding these is crucial for effective programming. Below, is a non-exhaustive list of Python data types:
- String (
str
): Textual data enclosed in quotes. E.g.,greeting = "Hello, World!"
- Integer (
int
): Whole numbers without a fractional component. E.g.,age = 25
- Float (
float
): Numbers with a decimal point. E.g.,height = 5.9
- Boolean (
bool
): RepresentsTrue
orFalse
- List (
list
): An ordered collection of items that can be of mixed data types. Lists are mutable, allowing modification. For example,colors = ["red", "blue", "green"]
- Dictionary (
dict
): A collection of key-value pairs, allowing you to store and retrieve data using keys. For example,person = {"name": "Alice", "age": 30}
For more on data types, read this Data Structures in Python tutorial on DataCamp.
Why Convert a String Into an Integer?
Correct data types are essential for accurate calculations. Consider the following example. Let’s assume we have two numbers 5
and 10
which are strings. If we add them together, the answer would be 510
, since they are being treated as strings that get concatenated with the +
operator.
To get the accurate answer (in this case 15
), they would need to be converted to integers before calculating the sum. This is a simple illustration, but imagine this is applied to a dataset of company revenue—this can lead to bad business decisions.
# Summing two numbers that are actually strings
'5'+'10'# This returns 510
# Converting them to integers before summing them
int('5') + int('10') # This returns 15
How to Convert Strings Into Integers in Python
When working with numerical data that are formatted as strings, it's often necessary to convert these strings into integers for calculations or other numerical operations. Python provides a straightforward way to achieve this using the int()
function. This function takes a string as input and returns its integer representation, provided the string represents a valid whole number.
# Convert a string to an integer
numeric_string = "42"
converted_integer = int(numeric_string)
print(converted_integer) # Output: 42
How to Convert Strings Into Floats in Python
In cases where the string represents a number with a decimal point, converting it to an integer would be inappropriate and result in an error. Instead, you can convert these strings to floats using the float()
function in Python. Using float data types is crucial especially when working with highly precise data, such as financial data or sensor measurement data.
# Convert a string to a float
decimal_string = "3.14"
converted_float = float(decimal_string)
print(converted_float) # Output: 3.14
Issues When Converting Strings to Numericals in Python
When converting strings to numbers, a few pitfalls can lead to errors or unexpected results.
Converting non-numeric strings
Attempting to convert a non-numeric string, like 'hello world'
, to a number will raise an error. If you want to programmatically catch strings that can’t be converted to integers, try using a try/except
block to handle such cases gracefully.
try:
invalid_number = int("hello world")
except ValueError:
print("This is not a number.")
Converting float strings to integers
Converting a string representing a float directly into an integer results in a ValueError
. While you can convert a string representing an integer into a float, you cannot do the opposite. Here’s an example of the error you can get:
string_decimal = '13.5'
# Convert string_decimal into an integer
int(string_decimal)
# Returns ValueError: invalid literal for int() with base 10: '13.5'
Strings with different bases
When we talk about "bases" in numbers, we're referring to the numbering system in which the number is expressed. The most common base is 10, also known as the decimal system, which is what we use in everyday life. It consists of 10 digits, from 0 to 9.
However, other bases exist and are used in various fields, particularly in computing. For example:
- Binary (Base 2): Uses only 0 and 1. It's the fundamental language of computers.
- Octal (Base 8): Uses digits from 0 to 7. It's less common today but was used in older computing systems.
- Hexadecimal (Base 16): Uses digits from 0 to 9 and letters from A to F (where A=10 and F=15). It's widely used in computing, especially for color codes in web design and memory addresses.
When you have a string representing a number in a base other than 10, you need to specify the base so Python can interpret it correctly. Here's an example using a hexadecimal number:
# Convert a hexadecimal string to an integer
hex_string = "1A" # In base 16, 1A represents the decimal number 26
converted_int = int(hex_string, 16) # The '16' tells Python it's in base 16
print(converted_int) # Output: 26
Conclusion
Navigating data types and conversions in Python is a foundational skill for programming. By understanding how to accurately convert strings to integers and floats, you can avoid common pitfalls and ensure your data manipulation is correct. If you want more on Python, check out our Python Cheat Sheet for Beginners, our guide on How to Learn Python, and our Python Courses.

Adel is a Data Science educator, speaker, and VP of Media at DataCamp. Adel has released various courses and live training on data analysis, machine learning, and data engineering. He is passionate about spreading data skills and data literacy throughout organizations and the intersection of technology and society. He has an MSc in Data Science and Business Analytics. In his free time, you can find him hanging out with his cat Louis.
FAQs
How to check if a string is an integer in Python?
To check if a string represents an integer, you can use the str.isdigit()
method if the string contains only digits and no sign (+/-) or decimals:
string = "42"
if string.isdigit():
print("The string is an integer.")
else:
print("The string is not an integer.")
For strings that may include a sign (+/-), you can use a more robust method:
string = "-42"
try:
int(string)
print("The string is an integer.")
except ValueError:
print("The string is not an integer.")
How to convert an integer to a string in Python?
Use the str()
function to convert an integer into a string. For example:
number = 42
string_number = str(number)
print(string_number) # Output: "42"
What should I do if the string contains a decimal number and I want to convert it to an integer?
First, convert the string to a float using the float()
function, then cast it to an integer using int()
. For example:
decimal_string = "13.5"
converted_integer = int(float(decimal_string))
print(converted_integer) # Output: 13