How to Concatenate Strings in Python

When programming in Python, strings and lists are two of the most common objects you'll encounter. Strings are immutable, meaning that they cannot be changed, while lists are not. A common task when you're programming is to concatenate, or add together, the contents of two strings. There are two ways to do this.

Step

Obtain the two or more strings. For example, to get the strings as input from a user, use raw_input:

Step

x = raw_input("Please enter first string: ") y = raw_input("Please enter second string: ")

Step

Concatenate the strings as string objects. Strings may be immutable, but they can be concatenated and appended to. To concatenate the two examples in Step 1, use the following:

Step

z = x + y print z

Step

Convert the strings to lists, concatenate their contents, then convert back to a string. Using the same example:

Step

a = list(x) b = list(y) c = a + b z = ''.join(c) print z

Step

The .join method joins the members of list "c" -- "a" and "b" concatenated -- with the delimiter inside the quotes -- in this case, an empty string -- and creates a new string, "z."