How to Add an Int to a String in Python

In Python programming, working with different data types is a common task. One of those tasks you might find yourself needing to handle is the addition of an integer to a string.

This task may seem simple, but Python deals with integers and strings differently. In this tutorial, we will delve into how you can go about combining both an integer and a string in Python.

Understanding Python Strings and Integers

A string is a sequence of characters that can be created by enclosing characters in quotes. Python treats single and double quotes as the same.

An integer, on the other hand, is a whole number (without a decimal point) that could be positive or negative. Integers in Python are of any length, the only limitation being the memory available.

In Python, strings and integers are defined as different data types. For example:

You cannot combine strings and integers directly.

Steps to add an Integer to a String in Python

To combine a string and an integer in Python, you either convert the integer into a string and then concatenate them together, or use the string formatting operation. Let’s consider each of these methods:

Method 1: Using the str() function for conversion

The str() function can turn an integer into a string, allowing you to concatenate them:

Output:

John has 20 years.

Method 2: Using String Formatting

The format() method can be used to add a string and an integer together:

Output:

John has 20 years.

Complete Code:

Conclusion:

Adding an integer into a string in Python can be achieved by converting the integer into a string or using string formatting techniques. The key is understanding that these are different data types and Python does not allow you to do certain operations across different types.