How to Concatenate Variables in Python?

Estimated read time 1 min read

To concatenate variables in Python, you can use the + operator for string concatenation or the str.join() method. Here are examples of both methods:

  1. Using the + operator:
# Concatenating variables using the + operator
variable1 = "Hello"
variable2 = "World"
concatenated = variable1 + " " + variable2


In the example above, the + operator is used to concatenate the variables variable1 and variable2, with a space in between.

  1. Using the str.join() method:
# Concatenating variables using str.join()
variable1 = "Hello"
variable2 = "World"
concatenated = " ".join([variable1, variable2])


In this example, the str.join() method is used to concatenate the variables variable1 and variable2. The method takes an iterable (in this case, a list containing the variables) and joins the elements together with the specified delimiter, which is a space in this case.

Note: It’s important to note that these methods work specifically for concatenating strings. If you want to concatenate variables of different types (e.g., numbers), you may need to convert them to strings using the str() function before concatenation.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply