Tutorials

How to Concatenate String and Int in Python (With Examples)

Introduction

Python supports string concatenation using the + operator. In most other programming languages, if we concatenate a string with an integer (or any other primitive data types), the language takes care of converting them to a string and then concatenates it.

However, in Python, if you try to concatenate a string with an integer using the + operator, you will get a runtime error.

Example

Let’s look at an example for concatenating a string (str) and an integer (int) using the + operator.

string_concat_int.py

current_year_message = ‘Year is ‘ current_year = 2018 print(current_year_message + current_year)

The desired output is the string: Year is 2018. However, when we run this code we get the following runtime error:

Traceback (most recent call last): File “/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py”, line 5, in print(current_year_message + current_year) TypeError: can only concatenate str (not “int”) to str

So how do you concatenate str and int in Python? There are various other ways to perform this operation.

In order to complete this tutorial, you will need:

This tutorial was tested with Python 3.9.6.

We can pass an int to the str() function it will be converted to a str:

print(current_year_message + str(current_year))

The current_year integer is returned as a string: Year is 2018.

We can pass values to a conversion specification with printf-style String Formatting:

print(“%s%s” % (current_year_message, current_year))

The current_year integer is interpolated to a string: Year is 2018.

We can also use the str.format() function for concatenation of string and integer.

print(“{}{}”.format(current_year_message, current_year))

The current_year integer is type coerced to a string: Year is 2018.

If you are using Python 3.6 or higher versions, you can use f-strings, too.

print(f'{current_year_message}{current_year}’)

The current_year integer is interpolated to a string: Year is 2018.

Displaying dynamic content (e.g., “You have X new messages”)

In web applications, it’s common to display dynamic content to users, such as the number of new messages they have. By concatenating strings and integers, you can dynamically generate messages like “You have X new messages” where X is the actual number of new messages.

Example:

new_messages_count = 5 message = “You have ” + str(new_messages_count) + ” new messages” print(message)

Creating log messages or reports

When creating log messages or reports, you often need to include specific data, such as dates, times, or numerical values. Concatenating strings and integers allows you to dynamically generate these messages with the correct information.

Example:

log_message = “Error occurred at timestamp: ” + str(timestamp) + ” with error code: ” + str(error_code) print(log_message)

Building strings for file names, database entries, etc

In various applications, you might need to generate file names or database entries dynamically. For example, you might want to save a file with a name that includes a timestamp or a unique identifier. By concatenating strings and integers, you can dynamically generate these file names or database entries with the required information.

Example:

file_name = “log_” + str(timestamp) + “.txt” print(file_name)

TypeError: must be str, not int

This error occurs when you try to concatenate a string with an integer using the + operator. To fix this, you need to convert the integer to a string using the str() function.

Example:

current_year_message = ‘Year is ‘ current_year = 2018 print(current_year_message + str(current_year))

Forgetting to cast int with str()

When concatenating strings and integers, it’s essential to convert the integer to a string using str(). Failing to do so will result in a TypeError.

Example:

new_messages_count = 5 message = “You have ” + str(new_messages_count) + ” new messages” print(message)

Misuse of + vs , in print()

In Python, when using print(), you can use either the + operator for string concatenation or the , operator for separating arguments. However, using + with integers will raise a TypeError. To fix this, use the , operator to separate arguments, which will automatically convert integers to strings.

Example:

print(“You have”, 5, “new messages”)

Method Example Pros Cons
+ Operator print(“Year is ” + str(2018)) Simple to use, easy to understand TypeError if not converted to string, less efficient for large strings
str() Function print(“Year is ” + str(2018)) Explicit conversion, easy to use Extra step required, less efficient for large strings
% Interpolation print(“%s%s” % (“Year is “, 2018)) Legacy support, simple to use Less readable, less flexible, less efficient, deprecated in Python 3.x
str.format() print(“{}{}”.format(“Year is “, 2018)) Flexible, readable, supports multiple arguments More verbose, less efficient for simple cases
f-strings print(f”Year is {2018}”) Most readable, flexible, efficient Python 3.6+ only, not suitable for older Python versions
, Operator print(“Year is”, 2018) Simple, readable, easy to use Only for print() function, not suitable for string concatenation in general

After evaluating the pros and cons of each method, it is clear that f-strings are the best method for concatenating strings and integers in Python. They are the most readable and flexible, and are supported in Python 3.6 and higher.

Why can’t I concatenate string and int in Python?

In Python, you cannot directly concatenate a string and an integer using the + operator because they are different data types. Python is a statically typed language, which means it checks the data type of variables at runtime. When you try to concatenate a string and an integer, Python throws a TypeError because it cannot implicitly convert the integer to a string.

Example:

print(“Year is ” + 2018)

How do I fix “TypeError: can only concatenate str (not ‘int’) to str”?

To fix this error, you need to convert the integer to a string using the str() function or f-strings. This allows Python to concatenate the string and the integer as strings.

Example:

print(“Year is ” + str(2018)) print(f”Year is {2018}”)

What is the best way to concatenate strings and numbers in Python?

The best way to concatenate strings and numbers in Python is to use f-strings. They are the most readable, flexible, and efficient method, especially for Python 3.6 and higher. F-strings allow you to embed expressions inside string literals, using curly braces {}.

Example:

print(f”Year is {2018}”)

Should I use +, str(), or f-strings in Python?

It depends on the Python version you are using and personal preference. For Python 3.6 and higher, f-strings are the recommended method due to their readability and flexibility. For older Python versions, using str() or the % interpolation method might be necessary.

Example:

print(“Year is ” + str(2018)) print(“Year is %s” % 2018)

How do f-strings work in Python?

F-strings work by embedding expressions inside string literals using curly braces {}. The expressions are evaluated and converted to strings, then inserted into the string at the corresponding position. This allows for dynamic string creation with embedded values.

Example:

current_year = 2018 print(f”Year is {current_year}”)

In conclusion, mastering string concatenation and manipulation is a crucial aspect of Python programming. By understanding the different methods of concatenating strings and numbers, including using the + operator, str() function, and f-strings, you can effectively create dynamic strings and improve the readability of your code. Additionally, learning about list concatenation, joining lists, and string functions can further enhance your skills in working with strings and lists in Python. For more in-depth tutorials on these topics, refer to the following resources:

These tutorials will provide you with a comprehensive understanding of working with strings and lists in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button