Skip to content

Python concatenate variables

  • by

You can concatenate variables using the + operator (combine two or more strings) in Python. The + operator should appear between the two variables you want to merge.

Python concatenate variables

Simple example code.

a = 'lemon'
b = 'lime'
soda = a + b

print("concatenate variables", soda)

Output:

Python concatenate variables

Concatenate strings and variables in Python

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)

print(my_string)

Output: a,b,c,d

If the variables are not strings, you may need to convert them to strings using the str() function before concatenating:

# Define variables
var1 = 10
var2 = 20

# Concatenate variables after converting to strings
result = str(var1) + " " + str(var2)

# Print the result
print(result)

Here, var1 and var2 are integers, so they are converted to strings using the str() function before concatenating.

Do comment if you have any doubts or suggestions on this Python concatenate topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading