Various Ways to Concatenate Strings in Python
This article reviews eight common Python string concatenation techniques—including the + operator, commas, direct adjacency, % formatting, format(), join(), f‑strings, and the * operator—explaining their syntax, use cases, performance considerations, and recommendations for small versus large-scale concatenations.
Plus Concatenation
First method using the + operator:
<code>>> a, b = 'hello', ' world'
>>> a + b
'hello world'</code>Comma Concatenation
Second method using a comma in print :
<code>>> a, b = 'hello', ' world'
>>> print(a, b)
hello world</code>Note that using a comma creates a tuple when assigning:
<code>>> a, b
('hello', ' world')</code>Direct Concatenation
Third method, direct adjacency works with or without spaces:
<code>print('hello' ' world')
print('hello''world')</code>Percent Operator
Fourth method using the % operator, historically the only formatting method before Python 2.6:
<code>print('%s %s' % ('hello', 'world'))</code>format Method
Fifth method using the format method:
<code>print('{}{}'.format('hello', ' world'))</code>join Method
Sixth method using the built‑in join method:
<code>print('-'.join(['aa', 'bb', 'cc']))</code>f‑string
Seventh method using f‑strings (Python 3.6+):
<code>>> aa, bb = 'hello', 'world'
>>> f'{aa} {bb}'
'hello world'</code>Multiplication Operator
Eighth method using the * operator:
<code>>> aa = 'hello '
>>> aa * 3
'hello hello hello '</code>Summary
For concatenating a small number of strings, the + operator is recommended. If performance is critical and you are using Python 3.6 or newer, f‑strings provide better readability. When dealing with many strings, prefer join (or f‑strings) depending on the Python version and readability requirements.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.