How To Concatenate String and Int in Python?

How To Concatenate String and Int in Python?

In Python, you can merge an integer and a string together using the `str()` function. This function turns the integer into a string, and then you can use the `+` symbol to join these strings. This makes it simple to mix numbers and words when you’re working with text in Python.

Let’s understand string and int concatenation by example.

Example:

string = 'Year is '
year = 2023
print(string + year)

Output:

string and int

Explanation:

The expected output is “Year is 2023”, but an error occurs because of an attempt to concatenate a string and an integer value in the code. So, how can we combine a string and an integer? There are multiple methods to achieve this. Let’s explore these methods one by one.

Save $100 in the next
5:00 minutes?

Register Here

Method 1: Using the “str()” method

string = 'Year is '
year = 2023
print(string + str(year))

Output:

Explanation:

Concatenates string and year after converting the integer year to a string using str(year). The str() function converts the integer to a string. The + operator then combines the two strings.

Method 2: Using the % Interpolation Operator

string = 'Year is '
year = 2023
print("%s%s" % (string, year))

Output:

string and int

Explanation:

It uses the % operator for string formatting. The %s is a placeholder for strings, indicating where the string and year variables will be inserted into the format string.

To concatenate a string and an integer in Python, convert the integer to a string using str() and then use the + operator to join them.

Method 3: Using the string.format() function

string = 'Year is '
year = 2023
print("{}{}".format(string, year))

Output:

Explanation:

This uses {} as a placeholder within the string. The format() method replaces these {} placeholders with the values provided in the format() function.

String and year are passed as arguments to format(). They correspond to the placeholders {} in the same order.

Method 4: Using f-strings

string = 'Year is '
year = 2023
print(f"{string}{year}")

Output:

Explanation:

The f at the beginning of the string denotes an f-string. Inside the f-string, {string} and {year} are placeholders that the variables string and year values will replace. When the code is executed, Python replaces {string} with the value of the variable string and {year} with the variable year’s value, concatenating these values.

Save $100 in the next
5:00 minutes?

Register Here

Conclusion:

In Python, concatenating a string and integer requires converting the integer to a string explicitly using functions like `str()`, f-strings (`f””`), or string formatting (`{}.format()`) and directly combining a string and int without conversion results in a type error due to their inherent incompatibility for direct concatenation. Explore the comprehensive collection of Python functions and discover more Python examples.