Append One String to Another in Python

The simplest way to append one string to another is by using the addition operator. The same as you use to add two numbers.

pre_text = "This is"
post_text = " text."
text = pre_text + post_text

print(text)

This code concatenates two strings and displays the result to the console.

This is text

Notice, that the post_text variable has a space before the text. It’s important for separating words.

If you have a list of words that you want to join, but there are no spaces between them, you can add words to a list and merge them with the join function.

pre_text = "This"
mid_text = "is"
post_text = "text."
text = " ".join([pre_text, mid_text, post_text])

print(text)

Space before join is a separator to separate the words. This is the result.

This is text.

Append Words using the For Loop

A string in Python is a list of characters. You can loop through each element of a string and add them to the end of another string.

pre_text = "This is"
post_text = " text."

for char in post_text:
    pre_text += char
    print(pre_text)

print("Final result:", pre_text)

With each step inside the loop, the variable is printed out to the console.

This is 
This is t
This is te
This is tex
This is text
This is text.
Final result: This is text.