Tutorial

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

Updated on May 2, 2025
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 <module>
    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.

Prerequisites

In order to complete this tutorial, you will need:

This tutorial was tested with Python 3.9.6.

Using the str() Function

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.

Using the % Interpolation Operator

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.

Using the str.format() function

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.

Using f-strings

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.

Practical Use Cases

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)  # Output: You have 5 new messages

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)  # Example output: Error occurred at timestamp: 1643723400 with error code: 500

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)  # Example output: log_1643723400.txt

Common Errors and Debugging

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))  # Corrected output: Year is 2018

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)  # Corrected output: You have 5 new messages

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")  # Corrected output: You have 5 new messages

Pros and cons of each method

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.

FAQs

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:

# This will raise a TypeError
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:

# Corrected using str()
print("Year is " + str(2018))
# Corrected using f-strings
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:

# Using f-strings
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:

# Using str() for older Python versions
print("Year is " + str(2018))
# Using % interpolation for older Python versions
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:

# Embedding an expression in an f-string
current_year = 2018
print(f"Year is {current_year}")  # Output: Year is 2018

Conclusion

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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Pankaj Kumar
Pankaj Kumar
See author profile
Category:
Tutorial
Tags:

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 17, 2019

Hey Pankaj, thanks for sharing this article. This helped me to have a better understanding of formats used with print function

- Anupinder singh

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    July 18, 2020

    Write a python program that asks the user how many coins of various types they have, and then prints the total amount of money in rupees.

    - M P ANUPAMA

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      September 8, 2021

      it works fine but takes too much time for instance if we have to convert integer to string 200 times , you would be able to notice the time taken to execute the code. How can we deal with that to make our code more efficient?

      - future googler

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 31, 2021

        num = ([3,4,3,2,1]) print(reduce(lambda x,y: x * 10 + y ,num)) 34321

        - Egmon

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.