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-A

Enthusiastic Network Engineer specializing in Cisco ACI, passionate about solving challenges. A lifelong learner who loves gaining and sharing knowledge. Profile: https://www.linkedin.com/in/bilel-ameur-71116b2b5
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x