Python
Strings
Integer Concatenation
Programming
Code Duplication

Python strings and integer concatenation

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Python does not implicitly concatenate strings with integers, and that is a deliberate design choice to prevent silent type bugs. You must convert values or use formatting tools that define output explicitly. Choosing the right style improves readability and avoids fragile string-building logic.

Core Sections

1. Why direct concatenation fails

This expression raises TypeError:

python
count = 5
# text = "items: " + count

+ between str and int is undefined because Python requires explicit representation choices for numbers.

2. Practical concatenation patterns

Pattern A: explicit str conversion

python
count = 5
text = "items: " + str(count)
print(text)

Simple and clear for very short expressions.

Pattern B: f-strings

python
1name = "Alice"
2score = 97
3text = f"{name} scored {score}"
4print(text)

Most modern codebases prefer f-strings for readability.

Pattern C: format

python
1name = "Alice"
2score = 97
3text = "{} scored {}".format(name, score)
4print(text)

Still useful in code that targets older style conventions.

3. Numeric formatting during concatenation

Concatenation often needs formatting control, not just conversion.

python
1price = 19.9
2qty = 3
3
4print(f"Total: ${price * qty:.2f}")
5print("Total: ${:.2f}".format(price * qty))

Formatting specifiers prevent inconsistent display output.

4. Join mixed collections efficiently

For many pieces, convert then use join instead of repeated +.

python
parts = ["id", 42, "ok", 3.14]
line = "-".join(map(str, parts))
print(line)

This is cleaner and avoids repeated intermediate string allocations.

5. Loop patterns and performance

In loops, repeated + can be inefficient for large output construction. Build list of fragments and join once.

python
1chunks = []
2for i in range(5):
3    chunks.append(f"item:{i}")
4
5result = "|".join(chunks)
6print(result)

For occasional concatenation, performance difference is negligible. For heavy loops, this pattern is safer.

6. Input validation before formatting

When numbers come from user input, convert and validate first.

python
1def build_message(raw_count):
2    try:
3        count = int(raw_count)
4    except ValueError:
5        return "invalid count"
6    return f"items: {count}"
7
8print(build_message("7"))
9print(build_message("abc"))

This keeps formatting code predictable and error handling explicit.

7. Logging and machine-readable outputs

For logs and integrations, ad hoc concatenation can produce ambiguous strings. Prefer structured output where possible.

python
1import json
2
3payload = {"user_id": 42, "status": "active"}
4print(json.dumps(payload))

Structured logs are easier to parse, search, and validate.

8. Internationalization considerations

Manual concatenation is risky for localized user-facing text because word order differs across languages. Use localization templates so translators control sentence structure.

Keep simple concatenation for internal diagnostics, not translated UI text.

9. Type-hinting and API boundaries

Strong typing at function boundaries reduces accidental concatenation bugs.

python
def format_order_count(count: int) -> str:
    return f"orders: {count}"

Type hints do not enforce at runtime by themselves, but they help static tooling catch wrong call patterns early.

10. Build formatting helpers once for consistency

In larger codebases, repeated ad hoc concatenation creates inconsistent output styles. A small shared formatter module for counts, currency, and identifiers keeps output behavior consistent across CLI commands, logs, and APIs. Centralized formatting also makes future localization or style changes significantly easier.

Common Pitfalls

  • Concatenating strings and integers directly with +.
  • Overusing manual conversion when f-strings are clearer.
  • Forgetting numeric formatting for currency or precision-sensitive output.
  • Building long strings with repeated + in loops.
  • Mixing human-readable strings with machine-parsed output formats.

Summary

  • Python requires explicit conversion or formatting for mixed string and integer output.
  • F-strings are usually the most readable default.
  • Use formatting specifiers for precise numeric representation.
  • Use join for multi-fragment string assembly.
  • Prefer structured formats for logs and external interfaces.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.