Skip to content

Python concatenate string and variable

  • by

You can use the ‘+’ operator to concatenate strings and variables in Python. But concatenate string and integer variable, you need to convert integer variable to string and then concatenate using the ‘+’ operator.

If you want a merge 2 strings and store value in another variable then use new_String= first_string + second_string.

Python concatenates string and variable

Simple example code.

var1 = 100
var2 = ' John'

# concatenation string and string variable
res1 = 'Hello' + var2
print(res1)

# concatenation string and int variable
res2 = str(var1) + var2
print(res2)

Output:

Python concatenate string and variable

If you try to combine a string and a number, Python will give you an error:

x = 5
y = "John"
print(x + y)

Output: TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

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

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