← Home

030. String Concatenation

Build strings by joining pieces

030. String Concatenation

RAM Manager — Building Alert Messages

Aryan’s RAM manager formats alert messages when a process exceeds its memory limit. An alert looks like:

[ALERT] chrome (PID 812) is using 544 MB — above limit of 500 MB

He builds it with string concatenation. But his format string is missing the space after "[ALERT]" and the (PID " separator between the process name and PID. The result is "[ALERT]chrome(PID812) is using..." — everything runs together.

The lesson: String concatenation (+) joins strings exactly as written. Spaces, punctuation, and separators must be added explicitly as string literals. A missing " " or "@" silently produces a malformed string — no error, just wrong output.


💡 Fun fact: Concatenating strings in a loop with += is O(n²) in Python because each operation creates a brand-new string and copies all previous content. For building large strings from many pieces, "".join(parts) is O(n) — it pre-calculates the total length and allocates exactly once. This difference becomes critical when building strings of thousands of pieces.

⚠️ Watch out: "Hello " + 42 raises a TypeError — Python will not silently convert the integer to a string like JavaScript would. You must always call str(42) explicitly, or better yet, use an f-string which handles the conversion for you.

🤔 Think about it: You can build the same string with + concatenation, "".join(), or an f-string. Each has a different readability and performance profile. For a greeting with 2-3 variables, which would you choose, and at what point would your choice change?

Learning objectives

  • Join strings with + operator
  • Add spaces and punctuation explicitly
  • Know when to prefer f-strings over concatenation

Key concepts

  • string concatenation
  • string building

Try it

Concept detail

String concatenation (+) joins two strings into a new string. It copies both strings. Concatenating many strings in a loop is O(n²) — use join() instead.

  • only works between two strings (no auto-conversion): “Hello “ + 42 raises TypeError. Convert numbers first: “Score: “ + str(42). For complex string building, f-strings or .format() are more readable: f“Good {time_of_day}, {name}!” is clearer than “Good “ + time_of_day + “, “ + name + “!”.

Solution

def full_name(first, last):
    return first + " " + last

def greeting(name, time_of_day):
    return "Good " + time_of_day + ", " + name + "!"

def build_email(username, domain):
    return username + "@" + domain

Tests

def test_full_name():
    assert full_name("Ada", "Lovelace") == "Ada Lovelace"

def test_greeting_morning():
    assert greeting("Alice", "morning") == "Good morning, Alice!"

def test_greeting_evening():
    assert greeting("Bob", "evening") == "Good evening, Bob!"

def test_email():
    assert build_email("alice", "example.com") == "[email protected]"

Resources