PythonPython StringsPython string concatenation
How do you concatenate strings?
Question 64 of 88 · Updated
On this page
- 1. Combining strings with the + operator
- 2. Appending text with +=
- 3. Combining strings with non-string values
- 4. Combine many strings with join
- 5. Practical example: assemble a report from fragments
- 6. Why repeated concatenation can be expensive
- 7. Incremental construction with io.StringIO
- 8. Combine fixed text with variable fragments
- 9. Concatenation preserves code points, not normalized visual text
- 10. Choosing the right technique
- 11. Common mistakes
- Frequently asked questions
- How do I concatenate two strings in Python?
- How do I concatenate strings with a space?
- Does += modify the original string?
- How can I concatenate a list of strings?
- Is join always faster than +?
- Can concatenation combine strings and integers automatically?
- Interview-ready answer
- Official references
String concatenation combines two or more strings into a single string. In Python, use the + operator for a few strings, str.join() for a collection of string fragments, and a formatting expression when combining text with other kinds of values.
The result is a string value containing the supplied text in the specified order. Because str is immutable, concatenation does not change the original string values in place.
1. Combining strings with the + operator#
PYTHONfirst = 'Ada' last = 'Lovelace' print(first + ' ' + last) print('' + first, first + '')
Output:
Ada Lovelace
Ada AdaThe operator preserves the order of the operands. Python does not insert separators automatically: the space in the first result is a separate string operand.
The empty string is the identity element for concatenation. Adding it before or after a string preserves the same text value.
Concatenation differs from addition of numbers even though it uses the same operator. Combining the strings '2' and '3' produces '23', not the number 5.
The operator is left-associative, so a chain of ordinary additions groups from left to right. For pure string operands, the resulting code-point sequence is the same regardless of how the concatenation is grouped. However, intermediate operations can affect allocation and performance.
2. Appending text with +=#
PYTHONtext = 'cat' original = text text += 's' print(text, original)
Output:
cats catAugmented assignment updates the binding of text to a concatenated result. The name original still refers to the unchanged original string value.
The earlier mutability lesson explained object references and the distinction between mutation and rebinding. The practical rule here is that string concatenation is not list-style in-place extension. Python implementations can reuse objects or optimize storage when doing so preserves observable semantics; do not infer allocation behavior from the operator alone.
For a handful of additions, += is often readable. In a loop that builds a large result, consider the total volume of intermediate copying before using repeated +=.
3. Combining strings with non-string values#
PYTHONcount = 3 print('Items: ' + str(count)) print(f'Items: {count}')
Output:
Items: 3
Items: 3The first expression explicitly converts an integer to a string. The f-string instead formats the value into the surrounding text.
Python does not automatically convert arbitrary numbers or bytes into str operands for ordinary string concatenation. The expression 'Items: ' + 3 raises TypeError. Text and binary data also have distinct representations: use the documented encoding to decode bytes when the intended result is text.
Choose conversion according to the output contract. The ordinary string representation of an object may not be an appropriate identifier, decimal representation or serialization format. In particular, converting None to text produces 'None' rather than an empty string. For optional values, decide explicitly whether to reject, omit or represent them.
The f-string and formatting lessons discuss numeric precision, field alignment and related formatting controls separately.
4. Combine many strings with join#
PYTHONparts = ['red', 'green', 'blue'] print(', '.join(parts)) print(''.join(parts)) print(repr(' / '.join([])), repr(' / '.join(['one'])))
Output:
red, green, blue
redgreenblue
'' 'one'The receiver of join is the separator. It inserts that separator between consecutive elements, not before the first or after the last.
An empty separator performs direct concatenation of all supplied fragments. Joining an empty iterable returns an empty string, and joining one string returns its text value without adding a separator.
Every element of the iterable must be a string. The method does not silently convert arbitrary objects. It accepts iterables of strings, including tuples and generators; it is not restricted to lists.
The dedicated join lesson later in this module will examine iterable handling, element validation and separator semantics in greater detail. This lesson uses join primarily as an alternative to repeated concatenation.
5. Practical example: assemble a report from fragments#
PYTHONdef build_message(records): parts = [] for name, count in records: parts.append(f'{name}: {count}') return '\n'.join(parts) print(build_message([('Pens', 2), ('Books', 4)])) print(repr(build_message([])))
Output:
Pens: 2
Books: 4
''The function builds each line independently and appends the resulting text to a list. It combines the completed fragments with a newline separator only once.
This design keeps record formatting separate from document assembly. It avoids a special conditional for the first newline and ensures that no extra trailing newline is introduced by the join operation.
The function assumes records supplies two-element entries that can be unpacked as name and count. It preserves record iteration order. A production reporting interface may additionally require a fixed numeric format, escaping of embedded separators, size limits or validation of record contents.
For instance, if a name itself can contain a newline, the report may contain additional lines. String concatenation does not automatically quote or escape values for an external format. Use a dedicated serializer for CSV, JSON and other structured representations.
6. Why repeated concatenation can be expensive#
Consider a loop that appends one nonempty fragment at a time to an initially empty string. If each addition copies all preceding content along with the new fragment, progressively longer intermediate results are created.
For n fragments of equal length m, the conceptual copy work under that model is:
m + 2m + 3m + ... + nm
= m * n * (n + 1) / 2That is O(m*n²) cumulative copying, even though the final text contains only m*n code points.
Collecting fragments and joining them can instead determine and construct the combined text without repeatedly copying every previous prefix. With k fragments and L output code points, a conventional cost estimate for a join of already available ordinary strings is O(k + L). The k term accounts for visiting the fragments, including empty ones. L includes the separator occurrences.
The diagram illustrates a possible repeated-copy execution model, not a guarantee about the exact allocations made by every Python interpreter.
CPython has optimizations for certain string append patterns, especially when references and execution conditions permit storage reuse. Therefore it is not correct to claim that every loop using += is necessarily quadratic, or that join is faster in every workload.
The robust engineering recommendation is to prefer a clear one-shot assembly strategy when many fragments form one result, and measure representative inputs before making a performance claim. Include the cost of creating fragments, converting inputs and allocating the final result.
If two ordinary strings have lengths n and m, a concatenation that copies both generally takes O(n + m) time and resulting storage under a bounded-cost code-point model. Empty operands, object reuse and implementation-specific optimizations can change particular cases.
7. Incremental construction with io.StringIO#
PYTHONfrom io import StringIO with StringIO() as buffer: for part in ['A', 'é', '🙂']: buffer.write(part) result = buffer.getvalue() print(result, len(result))
Output:
Aé🙂 3StringIO is an in-memory text stream. Its write interface is useful when a producer naturally emits several pieces of text at different points rather than returning one complete fragment collection.
The example writes three strings and obtains the assembled value before closing the buffer. StringIO operates on text, not encoded bytes. Its internal storage and copying behavior are implementation details; the final string and any retained buffer storage still contribute to the memory footprint.
For a single collection of strings, join is generally the simpler expression. For a component designed around text-writing interfaces, StringIO can provide a convenient file-like destination.
When the result is too large to hold comfortably in memory, writing incrementally to an actual text file or another appropriate stream may be preferable to constructing one giant string. That approach requires a destination encoding, error handling and an explicit policy for partial writes or failed operations.
8. Combine fixed text with variable fragments#
PYTHONdef assemble(prefix, parts): return prefix + ''.join(parts) print(assemble('ID:', ['A', '12'])) print(assemble('ID:', []))
Output:
ID:A12
ID:The function combines an arbitrary number of fragments using join, then adds a fixed prefix using +. The two techniques complement each other.
Its contract assumes prefix and every fragment are strings. It preserves the supplied iteration order. When the fragment iterable is empty, the result is simply the prefix.
Adjacent literals, such as 'ID' ':' in Python source, are another way to express fixed text. That is source-level literal concatenation, covered in the earlier string-quotation lesson. It cannot directly replace runtime addition of two variables.
9. Concatenation preserves code points, not normalized visual text#
PYTHONleft = 'e' right = '\u0301' import unicodedata text = left + right print(len(text), text == 'é') print(unicodedata.normalize('NFC', text) == 'é')
Output:
2 False
TrueThe two input strings form a decomposed sequence consisting of a base letter and a combining accent. They can display together as one grapheme cluster, but the concatenated value contains two code points.
Concatenation does not automatically normalize Unicode. The ordinary comparison with a precomposed é is therefore false. Applying NFC produces the canonically equivalent precomposed form in this example.
This also shows that a grapheme cluster can span the boundary between concatenated fragments. The number of visually perceived characters in the result is not necessarily the sum of the number of visible characters in each fragment considered separately.
Apply normalization only when the application explicitly requires it. Exact preservation of original code-point sequences may be important for identifiers, signatures and external protocol data.
10. Choosing the right technique#
| Technique | Suitable use | Important consideration |
|---|---|---|
| a + b | A few known string operands | Separators must be explicit |
| s += fragment | Simple, modest incremental updates | Repeated copying can be costly |
| sep.join(parts) | Combining many text fragments | All items must be strings |
| f-string | Interpolating values into readable text | Formatting rules determine representation |
| io.StringIO | Incremental text-writing interface | In-memory buffer and result require storage |
| Write to a destination stream | Large output that need not be retained as one string | Define encoding and partial-failure behavior |
Printing several arguments with print(a, b) is not the same as concatenating strings. Print writes a representation of the arguments to a stream using its separator and end parameters, and normally returns None rather than the assembled text.
The appropriate technique depends on whether the result is a value to return, a message to format, a large document to build, or output that can be streamed.
11. Common mistakes#
The following four invalid operations were tested independently and raised TypeError.
| Operation | Why it fails |
|---|---|
'a' + 1 | An integer is not an ordinary string operand |
'a' + b'b' | str and bytes are distinct representations |
''.join(['a', 1]) | The iterable contains a non-string element |
''.join([b'a']) | A bytes fragment is not str |
Other mistakes include expecting automatic spaces, omitting a required trailing delimiter, discarding the result of a string operation, and repeatedly rebuilding large prefixes without considering performance.
Do not use concatenation to insert untrusted values directly into executable SQL, shell commands or markup. Concatenation only combines text; it does not provide contextual escaping or security. Use parameterized database operations, argument-vector interfaces or a suitable escaping and serialization mechanism.
Test empty input, one fragment, multiple fragments, empty fragments, non-ASCII text and separators. When input may contain unexpected object types, validate the intended conversion policy rather than silently discarding values.
Frequently asked questions#
How do I concatenate two strings in Python?#
Use a + b. For ordinary str operands, the resulting text contains a followed by b.
How do I concatenate strings with a space?#
Use a + ' ' + b for two operands, or ' '.join(parts) for multiple strings.
Does += modify the original string?#
No. Strings are immutable. Augmented assignment rebinds the target to a concatenated result, preserving the original value for other references.
How can I concatenate a list of strings?#
Use ''.join(parts) without separators, or specify the separator string that should appear between fragments.
Is join always faster than +?#
No. A simple addition of two strings is usually clear and appropriate. Join is especially useful for avoiding repeated-prefix construction when combining many fragments. Actual performance depends on workload and interpreter behavior.
Can concatenation combine strings and integers automatically?#
Ordinary string addition does not perform that conversion. Convert the value explicitly using str, or use an appropriate formatting expression.
Interview-ready answer#
Python concatenates strings using the + operator, which combines their text in operand order without automatically adding separators. The += form updates a binding rather than mutating an existing string. For many fragments, separator.join(iterable) is usually preferable because it avoids the repeated-copy pattern of building a growing prefix; use StringIO for incremental text-writing interfaces. Non-string values require an explicit conversion or suitable formatting, and bytes must be handled according to their encoding. Concatenation preserves the original Unicode code-point sequences and does not normalize or escape them automatically. Consider output size, allocation behavior and representative benchmarks rather than assuming every += loop is quadratic.
Official references#
- Python Standard Library — Common Sequence Operations
- Python Standard Library — str.join
- Python Tutorial — Text
- Python Language Reference — Binary arithmetic operations
- Python Standard Library — io.StringIO
- Python Standard Library — unicodedata.normalize
- Python Standard Library — Text Sequence Type: str
Verification note: Eight runnable Python example groups matched their documented output in independent namespaces on CPython 3.13.5. Four expected TypeError tests and 1,000 seeded randomized assembly checks comparing join to explicit separator insertion and concatenation passed. Two fenced Mermaid diagrams were manually reviewed; the local Mermaid package and CLI were unavailable, so parser-level validation and public-site rendering were not performed. Complexity estimates are conditional models, not measured universal speedups. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Standard Library — Common Sequence Operationsdocs.python.org
- 2.Python Tutorial — Textdocs.python.org
- 3.Python Language Reference — Binary arithmetic operationsdocs.python.org
- 4.Python Standard Library — io.StringIOdocs.python.org
- 5.Python Standard Library — unicodedata.normalizedocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design