Beginner   Chapter 33 · 20 min read · Module 3: Python Strings

String Concatenation

Learning objectives
  • After this chapter you can join strings with the + operator.
  • You can repeat a string with the * operator.
  • You can convert numbers with str() before joining them to text.
  • You can build a string in a loop with += and with join().
  • You can choose the best joining method for a task.

Concatenation means joining strings together to make a longer string. When a program greets a user by name, builds a file path, or prints a sentence from several pieces, it is joining strings. Python offers several ways to do this, and each one has a good use.

The simplest tools are the plus operator, which joins two strings, and the star operator, which repeats a string. For joining many pieces, the join method is faster and neater. You will also meet the augmented operator += for building a string step by step.

In this chapter you will learn how to use +, *, += and join, why you cannot add a number to a string without converting it, and how to build longer text inside loops. You will also learn about implicit joining of string literals written side by side.

Joining with +

The + operator joins two strings and gives a new string. Python does not add any space, so you must include spaces yourself. The original strings are not changed, because strings are immutable.

Concatenation: joining two or more strings end to end to make a new string
Example 1: Joining strings
first = "Ada"
last = "Lovelace"
full = first + " " + last
print(full)
print(first + last)
print("Hi, " + first + "!")
Ada Lovelace AdaLovelace Hi, Ada!

Strings and numbers do not mix

If you try "Age: " + 30, Python raises a TypeError, because it will not guess how to join text with a number. You must convert the number to a string first with str(). Another option is to give print() several values separated by commas, which prints them with spaces and does not need any conversion.

Example 2: Converting a number
age = 30
try:
    print("Age: " + age)
except TypeError as error:
    print("Error:", error)
print("Age: " + str(age))
print("Age:", age)
Error: can only concatenate str (not "int") to str Age: 30 Age: 30

Repeating with *

Multiplying a string by an integer repeats it. "ab" * 3 gives ababab. A repeat count of 0 or less gives an empty string. This is handy for drawing lines of dashes or stars in text output. Both sides must make sense: a string times a string is a TypeError, and so is a string times a float.

Example 3: Repeating
line = "-" * 10
print(line)
print("ab" * 3)
print(repr("ab" * 0))
print("=" * 4 + " Menu " + "=" * 4)
---------- ababab '' ==== Menu ====

Building a string with +=

The operator += adds to the end of a string variable. The line s += "x" means s = s + "x". It really creates a new string each time, and the variable is then pointed at the new one. This is fine for small jobs. It is a common way to collect results in a loop.

Example 4: Building in a loop
result = ""
for i in range(1, 6):
    result += str(i)
    result += ","
print(result)
print(result[:-1])
1,2,3,4,5, 1,2,3,4,5

Joining many strings with join()

When you have a list of strings, separator.join(items) joins them all, placing the separator between items. It is the preferred method for many pieces because it is faster and shorter than a loop with +=. All items must be strings. The separator can be an empty string, a space, a comma, or any text.

Example 5: Using join
words = ["red", "green", "blue"]
print(" ".join(words))
print(", ".join(words))
print("".join(words))
print("-".join("abc"))
numbers = [1, 2, 3]
print("+".join(str(n) for n in numbers))
red green blue red, green, blue redgreenblue a-b-c 1+2+3
join is called on the separator, not on the list: write ", ".join(items), not items.join(", ").

Side-by-side literals

If you write two string literals next to each other with only spaces between them, Python joins them while reading your code. This is useful for splitting a long text over several lines inside parentheses. It works only with literals, not with variables.

Example 6: Implicit joining
message = ("Python is "
           "easy to read "
           "and fun.")
print(message)
print("one" "two")
Python is easy to read and fun. onetwo
Example 7: Greeting from input
name = input()
city = input()
print("Hello, " + name + " from " + city + "!")
Hello, Maya from Pune!

Which method should you choose?

  • Use + for joining two or three pieces.
  • Use * to repeat a pattern.
  • Use join for a list of strings or many pieces.
  • Use f-strings (a later chapter) when mixing text and values.

Order of operations and common patterns

When you mix operators in one line, Python follows the usual order: repetition with * happens before joining with +. So "=" * 3 + ">" gives ===>. Use parentheses when you want to repeat a joined piece, as in ("ab" + "-") * 2, which gives ab-ab-. Reading the line step by step, in the same way Python does, is the best way to predict the result.

A common pattern is to build a sentence from user input and fixed words. Another is to prepare a label with a repeated border around it. Both use only the three tools in this chapter. As you grow more comfortable, you will often replace long chains of + with f-strings, but the ideas here still sit underneath them, so it is worth knowing them well.

Remember that a string you build is still just a string. You can index it, slice it and measure it with len(), exactly like any other string. For example, the length of a joined string is the sum of the lengths of its parts, and the length of a repeated string is the repeat count times the original length.

Remember that every join makes a new string. For a small program this does not matter, but when you build very large text, collecting pieces in a list and calling join once at the end is the better habit.

Python syntax

Syntax
a + b
Syntax
text * count
Syntax
text += more
Syntax
separator.join(list_of_strings)

Real-world applications

  • Building a greeting from a name typed by the user.
  • Drawing separator lines such as '=' * 30 in console reports.
  • Joining words from a list into a sentence or a CSV line.
  • Creating file paths and messages from several parts.

Common mistakes

Mistake: Joining a string and a number with +, as in 'Total: ' + 5.
Fix: Convert the number first: 'Total: ' + str(5).
Mistake: Forgetting the spaces, so 'Hello' + 'World' prints HelloWorld.
Fix: Add the space yourself: 'Hello' + ' ' + 'World'.
Mistake: Calling join on the list, as in items.join(', ').
Fix: join belongs to the separator string: ', '.join(items).
Mistake: Passing numbers to join, as in ','.join([1, 2]).
Fix: Convert them first: ','.join(str(n) for n in numbers).

Important tips

  • Use join instead of += when combining many pieces from a list.
  • Print a repeated line like '-' * 20 to make output easier to read.
  • Use print with commas when you only need to display mixed types.

Key points summary

  • + joins strings and * repeats them.
  • A string cannot be joined to a number without str().
  • += creates a new string each time.
  • separator.join(items) needs every item to be a string.
  • Concatenation never changes the original strings.

Exam and interview points

  • '3' + '4' gives '34' but 3 + 4 gives 7.
  • str * int repeats; str * str is an error.
  • ', '.join(list) puts the separator only between items.
  • Adjacent literals are joined at compile time.

Quick revision

  • + joins, * repeats.
  • Use str() for numbers.
  • join works on a list of strings.
  • += makes a new string.

Frequently asked questions

Why do I get TypeError when I add a number to a string?

Python does not guess whether you want text or arithmetic. Use str(number) to join, or int(text) if you want to add numbers.

Is + or join faster?

For two or three pieces they are similar. For many pieces, join is faster because it builds the final string once.

What does 'ab' * 0 give?

An empty string. Any repeat count of zero or less gives an empty string.

Can I multiply a string by a float?

No. The repeat count must be an integer, otherwise Python raises TypeError.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters