Trusted answers to developer questions

How to concatenate strings in Python

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

In Python, you can concatenate two different strings together and also the same string to itself multiple times using + and the * operator respectively.

Use the + operator

The + operator can be used to concatenate two different strings.

The following illustration shows how it is done:

1 of 3
str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str=str1+str2
print("Concatenated two different strings:",str)

Use the * operator

Appending the same string to a string can be done using the * operator, as follows:

str=str * x
  • Where x is the number of times string str is appended to itself.

The following illustration shows how it is done:

1 of 3
str1="Hello"
print ("String 1:",str1)
str1=str1*3
print("Concatenated same string:",str1)

Note: When concatenating a variable of non-string type with a string, you first need to cast that variable into a string.

RELATED TAGS

python
concatenation
append
prepend
join
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?