HomeTutorialsPython

# How to Convert a String into an Integer in Python

Learn how to convert Python strings to integers in this quick tutorial.
Apr 2024

One of the most common obstacles in Python, especially for beginners, is data type errors. A really common data type error happens especially 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: Here’s How You Convert a Python String to an Integer

If you’re in a hurry, here’s the quickest solution to convert a string to a numeric type in Python. 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``````

## About 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`): Represents `True` or `False`
• 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, incorrect insights here 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``````

## Common Issues

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``````

## Final Thoughts

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.

Author

Adel is a Data Science educator, speaker, and Evangelist at DataCamp where he 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.

Topics

Continue Your Python Learning Journey Today!

Course

### .css-1531qan{-webkit-text-decoration:none;text-decoration:none;color:inherit;}Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See Details
Start Course

Course

### Intermediate Python

4 hr
1.1M
Level up your data science skills by creating visualizations using Matplotlib and manipulating DataFrames with pandas.

Track

### Data Manipulation

16hrs hr
Take the pain out of data manipulation using pandas. You’ll learn how to transform, sort, and filter data in DataFrames, ready for quick analysis.
See More
Related

tutorial

### How to Convert a List to a String in Python

Learn how to convert a list to a string in Python in this quick tutorial.

tutorial

### Python String format() Tutorial

Learn about string formatting in Python.

DataCamp Team

5 min

tutorial

### Python String to DateTime: How to Convert Strings to DateTime Objects in Python

In the tutorial, learn everything about the Python datetime module. Find a step-by-step guide for strings to datetime conversion, along with code samples and common errors.

Arunn Thevapalan

9 min

tutorial

### Python Concatenate Strings Tutorial

Learn basic concepts of string manipulation in Python.

DataCamp Team

1 min

tutorial

### Python Count Tutorial

Learn how to use the counter tool with an interactive example.

DataCamp Team

3 min

tutorial

### How to Trim a String in Python: Three Different Methods

Learn the fundamentals of trimming leading and trailing characters from a string in Python.