How To Print A String And An Integer Together In Python

To print a string and an integer together in Python, you can use some methods such as using the str() function, the % Interpolation Operator, the format() function, and the f-strings. Please read the article for more detail.

To print a string and an integer together in Python.

Using the str() function

First, we will introduce you to use the str() function to print a string and an integer together in Python. This function usually converts any data type to a string type.

Code Example

In this example, We use the str() method to convert the year variable and type of it is int into a string. Then we easily print out two strings.

Let’s see the code example below.

message = "Happy New Year "
year = 2023

# Using the str() function
print(message + str(year)) 

Output

Happy New Year 2023

Using the % Interpolation Operator

In a second way, we use the % interpolation operator. You can pass values to a conversion specification with printf-style. The % operator tells the Python interpreter to format a string using a given set of variables enclosed in a tuple, following the operator.

Example

Let’s see the example below to get more information.

message = "Happy New Year "
year = 2023

# Using the % Interpolation Operator
print("%s%s" % (message, year)) 

Output

Happy New Year 2023

Using the format() function

Next, we can also use the str.format() function to print a string and an integer together. You can use the format() function and {}{} to print them together. The format() method will return the formatted string. You can use it as follow syntax:

str.format(value1, value2...)

Example

Let’s see the example below to get more information.

message = "Happy New Year "
year = 2023

# Using the format() function
print("{}{}".format(message, year))

Output

Happy New Year 2023

Using the f-strings

The last way is to use the f-strings. We use the {} to force type in a string, then put an f in front of each line. As of Python 3.6, f-strings are a great new way to format strings

Example

Let’s see the example below to get more information.

message = "Happy New Year "
year = 2023

# Using the f-strings
print(f'{message}{year}')

Output

Happy New Year 2023

Summary

This article has already introduced many methods to print a string and an integer together in Python. But the str() function is the most suitable choice because it helps quickly convert int type to string and can easily print it together.

Leave your comment here if you have any questions about this article.

Thank you for reading!

Leave a Reply

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