Building Python Strings

Introduction

Welcome back to Performing Operations on Python Data! Having just wrapped up arithmetic operators, we're already off to a strong start in this course. Now, we'll shift our focus from numbers to text.

So far, we've stored strings and numbers in variables and printed them, but our messages have been fairly plain. Real programs often need to mix fixed text with values that change, such as a user's name or a price. To do this cleanly, Python gives us two handy techniques:

  • String concatenation with the + operator
  • f-strings, which let us embed variables directly inside text

Let's explore both, starting with the classic approach.

Joining strings with the + operator

The + operator is not just for numbers. When placed between two strings, it concatenates them, meaning it glues them together into a single new string. Let's build a friendly greeting for a user named Ada:

first_name = "Ada"

# Joining strings with the + operator
greeting = "Hello, " + first_name + "!"
print(greeting)

Here, we take three string pieces: the literal "Hello, ", the value stored in first_name, and the literal "!". Python glues them together in order, producing "Hello, Ada!", which we then print:

Hello, Ada!

Notice that we included the comma, the space after it, and the exclamation mark ourselves. The + operator joins pieces exactly as written, so if we forget a space, the words will run together like "HelloAda!".

The catch: concatenation only works with strings

Concatenation feels natural until we try to mix in a number. Suppose we add items = 3 and try to build a message like this:

items = 3
print("Items: " + items)  # This will fail!

Python raises a TypeError because it refuses to glue a string and an integer together directly. As we saw in an earlier course, we can convert the number using str():

print("Items: " + str(items))  # Works, but a bit clunky

That fix works, but imagine a longer message with several numbers mixed in. We'd need str() around each one, and the code would quickly become hard to read. There must be a better way — and there is.

Introducing f-strings

An f-string (short for formatted string) lets us embed variables directly inside a string. The rules are simple:

  1. Put the letter f right before the opening quote.
  2. Wrap any variable name in curly braces {} inside the string.

Let's use an f-string to build a purchase summary that mixes a string, an integer, and a float all at once:

items = 3
total = 29.97

# f-strings embed variables directly inside the text
print(f"{first_name} bought {items} items for ${total}.")

Python looks inside each pair of {}, replaces the variable name with its current value, and stitches everything into one clean string. Notice that the dollar sign right before {total} is just a regular character in the text, not part of the syntax.

Both techniques side by side

Let's run the full program with both techniques together and check what appears on the screen:

first_name = "Ada"
items = 3
total = 29.97

greeting = "Hello, " + first_name + "!"
print(greeting)

print(f"{first_name} bought {items} items for ${total}.")

The output is:

Hello, Ada!
Ada bought 3 items for $29.97.

Two lines, two techniques. The greeting was built by concatenating three string pieces, while the second line used a single f-string to weave together a string variable, an integer, and a float. With no str() calls or extra + signs, f-strings simply handled every type for us.

When to use each technique

Both techniques are valid Python, so which should we reach for? Here is a simple guideline:

  • Use + when joining just a couple of string pieces and no conversions are needed. It is short and readable in small doses.
  • Use f-strings when mixing multiple variables or different data types, or when we want the final message to read like a normal sentence with placeholders.

In practice, f-strings win most of the time. They keep the message's shape visible, avoid conversion errors, and scale well as messages grow. We recommend defaulting to f-strings for output going forward and reserving + for the occasional quick join.

Conclusion and next steps

Great work! We've added two important tools to our toolkit: joining strings with the + operator and embedding variables inside f-strings using {}. Along the way, we saw why concatenation stumbles on numbers and how f-strings sidestep that problem entirely by handling strings, integers, and floats without a fuss.

Up next, a set of hands-on practice tasks is waiting for you, where you will get to build and refine messages using both techniques on your own. Let's head into the practice and make these tools feel second nature!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal