STRING ADDITION IN PYTHON – CONCATENATION

Photo of author

By Jackson Taylor

Home » Electronics Topics » Python & OpenCv » STRING ADDITION IN PYTHON – CONCATENATION

String concatenation means joining two or more strings into one longer string. In Python the simplest way is the + operator, which is why people often call it “string addition”. This article shows how it works, what to watch out for, and which alternatives are better in different situations. If you are new to the language, it helps to start with getting started with Python first.

Program

Here is the original example. It stores text in two variables and joins them with +. The version below uses Python 3 syntax, where print is a function and needs parentheses. The original used the older Python 2 form, print b+a, which gives a syntax error in Python 3. Semicolons at the end of lines are not needed either.

a = '222'
b = '333'
print(b + a)

a = 'EMER'
b = 'GING'
print(a + b)

Because both values are strings, b + a prints 333222 rather than adding the numbers, and a + b prints EMERGING. To check how many characters a joined string ends up with, paste it into our string length counter; more small helpers for programmers are in the free online tools collection.

Why ‘222’ + ‘333’ is not 555

The quotes around '222' and '333' make them text, not numbers. Python treats text as a sequence of characters, so + places one after the other. The order matters: b + a puts b first, which is why the output is 333222 and not 222333.

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video

If you want real arithmetic, remove the quotes or convert the strings with int():

a = '222'
b = '333'
print(int(a) + int(b))   # 555

Adding spaces and separators

The + operator joins strings exactly as they are. It adds no space between them. If you want one, include it yourself:

first = 'Emerging'
second = 'Techs'
print(first + ' ' + second)   # Emerging Techs

The common TypeError

The most frequent mistake is joining a string with a number. Python does not convert types automatically here:

age = 25
print('Age: ' + age)
# TypeError: can only concatenate str (not "int") to str

There are two simple fixes. You can convert the number to a string, or use one of the formatting methods described below.

print('Age: ' + str(age))   # Age: 25

Other ways to combine strings

The + operator is fine for a few short pieces. For anything longer, these options are usually easier to read.

See also
IGBT BASED HEATER TEMPERATURE CONTROL SYSTEM FOR INFANT INCUBATORS (IEEE)

f-strings

An f-string (available in Python 3.6 and later) lets you put variables directly inside the text. It also converts numbers for you, so there is no TypeError.

name = 'Sam'
age = 25
print(f'{name} is {age} years old')

The format() method

The format() method works in older Python 3 versions too. Curly braces mark where each value goes.

print('{} is {} years old'.format(name, age))

The join() method

When you have a list of strings, join() combines them in one step. The string you call it on is placed between the items.

words = ['Python', 'string', 'concatenation']
print(' '.join(words))    # Python string concatenation
print('-'.join(words))    # Python-string-concatenation

Placing literals side by side

Two string literals written next to each other are joined automatically. This is handy for splitting a long line of text in your code, but it only works with literals, not variables.

text = 'Hello, ' 'world'
print(text)   # Hello, world

Building a string step by step

You can use += to add to an existing string. This is common when you build output inside a loop, for example a while loop in Python.

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works
result = ''
i = 1
while i <= 3:
    result += str(i) + ' '
    i += 1
print(result)   # 1 2 3

Strings in Python are immutable, which means every join creates a new string rather than changing the old one. For a handful of pieces this makes no practical difference. If you are combining a large number of strings in a loop, it is usually cleaner and faster to collect them in a list and call join() once at the end.

Repeating a string

The * operator repeats a string a set number of times. It is a quick way to make separators or simple patterns.

print('-' * 10)   # ----------

Using concatenation with user input

Concatenation is often used to build messages from what the user types. Anything typed in is received as a string, so there is no conversion needed when you join it with other text. The article on reading input in Python covers how that works, and if you want to see more ways to show results on screen, see printing strings, variables and constants.

name = input('Your name: ')
print('Hello, ' + name + '!')

Which method should you use?

  • + operator: good for joining two or three short strings.
  • f-strings: best for mixing text with variables and numbers.
  • join(): best for lists of strings or many pieces.
  • format(): useful if you need to support older code.
See also
HIGH VOLTAGE BUCK CONVERTER

FAQ

How do I concatenate two strings in Python?

Use the + operator: 'EMER' + 'GING' gives 'EMERGING'. You can also use an f-string or join().

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

Python will not mix types with +. Convert the number with str(), or use an f-string, which handles the conversion for you.

Does Python add a space when joining strings?

No. The strings are joined exactly as written. Add a space such as ' ' yourself, or use ' '.join(...) for a list of words.

Why does print b+a not work for me?

That is Python 2 syntax. In Python 3, write print(b + a) with parentheses.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works