How To Concatenate In Python Print

In this tutorial, we will learn how to concatenate strings, variables, and numbers in Python using the print function. Concatenation is a common task in programming where you join multiple strings together to create a combined string.

Python offers several ways to achieve this, but we will focus on using the print function.

Step 1: Using the Plus Operator (+) for String Concatenation

One of the simplest ways to concatenate strings in Python is using the plus operator (+). Let’s take a look at an example:

In this example, we join two strings string1 and string2 using the plus operator, and then we print the result using the print function. The output of this code will be:

Hello, world!

However, this approach does not work when you want to concatenate variables of different data types (e.g., integers and strings). In that case, you will need to convert the non-string data types to strings using the str() function, as shown in the following example:

The output of this code will be:

Hello, world! Today is day 5

Step 2: Using Format Strings (f-strings)

Introduced in Python 3.6, format strings (also known as f-strings) are an effective and concise way to concatenate strings, variables, and numbers. To create an f-string, prefix the string with an f or F character and place expressions within curly braces {}. Here’s an example:

The output of this code will be:

My name is John and I am 30 years old.

You can also include calculations and format specifiers within the curly braces. For example:

The output of this code will be:

The price is $49.99

Step 3: Using the str.format() Method

Another way of concatenating strings is using the str.format() method. This method replaces placeholders, specified by a pair of curly braces {}, with values provided as arguments to the format() function.

Here’s an example of using str.format():

The output of this code will be:

My name is Jane and I am 25 years old.

You can also use positional and keyword arguments to customize the order of replacement:

The output of this code will be:

My name is Jane and I am 25 years old.

Full Code

Here’s the full code from all the examples above:

Conclusion

In this tutorial, we explored three different ways to concatenate strings, variables, and numbers in Python using the print function: the plus operator (+), format strings (f-strings), and the str.format() method.

Depending on your specific use case and personal preference, any of these methods can be used to effectively concatenate data in Python.