Concatenate Text to variable in Python


Combine Variable Strings to text:

It’s quite easy to concatenate strings in Python, just add the “+” sign between the string variable.

x = "Python is "
y = "cool"
print(x + y)

or directly between Text and the string variable.

x = "cool"
print("Python is " + x)

#Python is cool



Concatenate Variable with “%” Operator , “%s” in Python:

x='Hello'
y='from the other side'
print("%s %s"%(x,y))

#Hello From the other side




Concatenate String to integer in Python:

When you combine string variables with integer or other types, an error will be raised:

TypeError: can only concatenate str (not “int”) to str

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


to overcome this error, you can convert the integer type to string type:

x = str(5)
y = "Alexa"
print(x + y)

Bilel

Bilel

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x