Concatenating Strings in Python

To concatenate two strings in Python, you can use the "+" operator (only works with strings). To concatenate strings and numbers, you can use the operator "%". To concatenate list items into a string, you can use the string.join() method. The string.format() method allows you to concatenate multiple variables into a string and format the result. Since Python 3.6, you can use f-strings to concatenate your strings. F-strings are similar to string.format(), but they are more concise, easier to read, and less error-prone when refactoring your code. In this Python Concatenate Strings example, we are using the "+" operator. The rest of Python's string concatenation methods are listed below, with detailed explanations and examples. Click Execute to run the Python String Concatenation example online and see the result.
Concatenating Strings in Python Execute
first_string = 'Hello'
second_string = 'World'

print(first_string + ' ' + second_string)
Updated: Viewed: 6998 times

What is Python?

Python is one of the most popular general-purpose programming languages ​​mainly used for server-side programming, machine learning, application testing, and as "glue code" that connects various components together. Python is an interpreted and object-oriented language with dynamic typing, dynamic binding with a built-in garbage collection. Python works with almost any operating system, including Windows, Linux, and macOS. Python is very easy to learn, and Python code is easy to maintain. Python has built-in modules for working with JSON, strings, HTTP requests, and XML out of the box.

What is a string in Python?

In Python 3, strings are an array of 16-bit Unicode bytes (and 8-bit ASCII bytes for Python 2). Each character in a string is denoted by one byte. String literals can be enclosed in double or single quotes. You can use single quotes within double-quoted strings and vice versa. Python doesn't have a separate type for a single character; such characters are represented as a one-character string of length 1. Characters in a string can be accessed by index using the "[]" operator.

Python strings are not mutable; once created, they cannot be changed. The string manipulation functions always create a new string instead of modifying the existing one. The built-in Python "str" library provides essential functions for searching, concatenating, reversing, splitting, and comparing strings.

How to concatenate two strings in Python?

The easiest and most commonly used way to concatenate two strings in Python is to use the ("+") operator. It concatenates or glues them together. To do this, you need to write two lines and a "+" sign between them.

Concatenate strings with "+" operator
a = 'Hello'
b = 'World'
print(a + b)

# output: HelloWorld

Note that the "+" operator adds nothing between or after these variables. Therefore, to make the text more readable, we need to use the "+" operator again to add a space.

Concatenate strings with a separator between them
a = 'Hello'
b = 'World'
print(a + ' ' + b)

# output: Hello World

How to concatenate strings and numbers in Python?

The "+" operator can only concatenate strings. If you try to join strings and numbers, you will get a TypeError exception.

Concatenating strings and numbers (wrong way)
a = 'Number: '
b = 12345

print(a + b)
# output: TypeError: can only concatenate str (not "int") to str

To concatenate a string and a number using the "+" operator, you first need to cast and convert the number to a string first. To do this, you can use the Python str() method, which takes a number as a parameter and returns it in string format.

Concatenating strings and numbers (correct way)
a = 'Number: '
b = 12345
print(a + str(b))

# output: Number: 12345

How to concatenate and format strings in Python?

The "%" operator allows you to concatenate and format strings. This operator replaces all "%s" in the string with the specified variables. First, you need to write the string you want to format, then the "%"" sign, and then the tuple of strings whose values you want to use.

Concatenate strings with "%" operator
name = 'John'
surname = 'Smith'
print('Hi, %s %s' % (name, surname))

# output: Hi, John Smith

This method has a drawback: long text with many variables can lead to hard-to-find errors when refactoring your code.

How to concatenate a list of strings in Python?

The string.join() method concatenates an iterable list of strings with a separator between them. The function takes an array of strings as a parameter, and the string value is used as a separator. A string of one or more characters can be used as a separator.

Concatenate strings with string.join()
numbers = ['One', 'Two', 'Three']
result = ', '.join(numbers)
print(result)

# output: One, Two, Three

Like the "+" operation, the string.join() method only works with strings and will throw a TypeError exception if it encounters a number in the list. You need to cast the number to string using str().

How to concatenate variables into a string and format the result?

The string.format() method creates formatted strings using a template string with placeholders and supplied variables. Placeholders are defined using curly braces {} and will be replaced by the supplied variables. Variables can be accessed both by index and by the variable name.

Concatenate strings with string.format() (basic example)
name = 'John'
surname = 'Smith'
result = 'Hi, {} {}'.format(name, surname)

print(result)

# output: Hi, John Smith

An example of accessing string.format() variables by index to concatenate strings.

Concatenate strings with string.format() (using variable index)
name = 'John'
surname = 'Smith'
result = 'Hi, {1} {0}'.format(name, surname)

print(result)

# output: Hi, Smith John

An example of accessing string.format() variables by name. This method is preferred when you are concatenating a large number of string variables.

Concatenating strings with string.format() (using named variables)
result = 'Hi, {name} {surname}'.format(name='John', surname='Smith')

print(result)

# output: Hi, John Smith

Unlike the "+" and "%" operators, the string.format() method can concatenate strings and numbers.

Concatenating strings and numbers with the string.format()
a = 'Number:'
b = 123
result = '{} {}'.format(a, b)

print(result)

# output: Number: 123

Concatenating strings using Python f-strings

F-strings, also called "formatted string literals", are string literals with a leading "f" and curly braces in the string pattern that will be replaced with the values of the variables. Internally, f-strings are Python expressions that will be evaluated at runtime, not a constant value.

F-strings are less verbose, more readable, and less error-prone when refactoring your code than other ways to concatenate strings. Whenever possible, prefer f-strings to any concatenation method.

Concatenating strings with f-stings
name = 'John'
surname = 'Smith'
result = f'Hi, {name} {surname}'

print(result)

# output: Hi, John Smith

Like the string.format() method, f-strings can concatenate strings and numbers.

Concatenating strings and numbers with f-stings
a = 'Number:'
b = 123
result = f'{a} {b}'

print(result)

# output: Number: 123

F-strings use the same rules as regular strings, raw strings, binary strings, and triple-quoted strings. The "f" can be combined with "r" in any order to produce raw f-string literals and cannot be combined with "b" and "u".

Conclusion

There are several ways to concatenate two or more strings in Python. The simplest and most commonly used method is the "+" operator. If you have a list of strings and want to concatenate them using the same separator between them, use the string.join() method. If you want to concatenate several variables to string and format that string, use the "%" operator or the string.format() method. If you are using Python 3.6 and above and want to build and format a string using multiple variables, use Python f-strings.

See Also