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’

Alternatively, you can use formatted strings (introduced in Python 3.6 and later) or the str.format() method for more readability:

Using formatted strings:

name = "Alice"
age = 25

# Using formatted string
message = f"Hello, my name is {name} and I am {age} years old."
print(message)

Using str.format() method:

name = "Alice"
age = 25

# Using str.format() method
message = "Hello, my name is {} and I am {} years old.".format(name, age)
print(message)

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