Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Working with Strings

Working with Strings 18 minA string is Python’s text type: an ordered sequence of Unicode characters.

A string is Python’s text type: an ordered sequence of Unicode characters.

Clean, slice, split and format text while tracking the boundaries and new strings each operation produces.

A form gives you characters; your program must decide which to preserve, remove, extract or display. Starting with simple text and indices, we will clean a name, select a suffix and split fields. Watch where a transformation loses information: a tidy-looking result is not automatically valid data.

The word CANTEEN in seven boxes with 0 to 6 written above and -7 to -1 below; the slice s[1:4] picks A, N, T in green, and box 4 is dashed red because the stop index is never included

Clean a name from a form

A sign-up form hands you whatever the person typed: " aSHA rao ". Before you save it, trim the spaces and fix the capitals:

python

Step through the chain and watch each step make a new string while raw stays as it was:

step through it
1raw = " aSHA rao "
2cleaned = raw.strip()
3titled = cleaned.title()
4header = f"Guest: {titled}"
5print(header)

Methods chain left to right: .strip() returns a string, and .title() runs on that. The same kit cleans an email, and in asks "is this text inside that text?":

python

Notice the line email = email.strip().lower(). Leave out email = and nothing happens:

What does this print?
name = "  asha rao "
name.strip()
print(f"[{name}]")
broken — fix it

This should print [Asha Rao]. It prints the raw input. Make the cleaning stick.

Choose the boundaries. Follow the selected positions.

A slice visits positions toward its stop boundary. The stop position is excluded; reversing the step changes the direction.

0C-7
1A-6
2N-5
3T-4
4E-3
5E-2
6N-1

s[1:4]→"ANT"

Interactive model of Python slicing over Unicode code points. A visible character may contain several code points. Blank bounds are omitted, which differs from explicitly using -1 with a negative step.

Preparing this topic’s interactive investigation…

Slices select between boundaries

For text = "PYTHON", six characters occupy indices 0 through 5. text[1:4] takes indices 1, 2, 3: its stop boundary is excluded. There are 4 - 1 = 3 characters. Think of cuts before and after characters, rather than two characters to include.

python

text[99] asks for one nonexistent item and raises IndexError. A slice can be empty or stop at the end, so it does not raise for these bounds. Negative indices count from the end: -1 is the last character. text[-4:] therefore returns the whole string when it has fewer than four characters; masking requires a separate length policy.

Mask a card number

A payment screen shows only the last four digits of a card: XXXXXXXXXXXX4444. The digits sit at positions 0 to 15, so the last four are at 12 to 15. First try:

What does this print?
card = "4111222233334444"
print(card[12:15])

Counting from the front is fragile anyway, because not every card has 16 digits. Count from the back instead. card[-4:] means "from the fourth-last to the end", whatever the length. And * repeats a string, + glues two:

python

Step through the masking one line at a time:

step through it
1card = "4111222233334444"
2last4 = card[-4:]
3hidden = "X" * (len(card) - 4)
4masked = hidden + last4
5print(masked)

The first idea most people have is to overwrite the front of the string:

broken — fix itTypeError

Run it and read the error. Then make it print the masked card.

Replacing the whole variable is fine. Reaching inside the characters is what Python refuses.

Split a dinner bill

Four friends type their names into a bill-splitting app as one line: "Asha,Ravi,Meena,Kabir". .split(",") cuts at every comma and gives you a list. .join() does the reverse, and the string you call it on is the glue that goes between the pieces:

python

After the colon inside { } comes a format spec: .2f means two decimal places, <8 and >9 set a width for tidy receipt columns. The f-string always makes new text; share itself is still the number 310.0.

Two things go wrong here all the time. If someone types spaces after the commas, .split(",") keeps them: "Asha, Ravi".split(",") gives ['Asha', ' Ravi'], with a sneaky space inside the second name. And people write .join() backwards:

broken — fix itAttributeError

Run it: lists have no join. Put the glue in front.

One-liners and traps

python

Trap: "Total: " + 250 is a TypeError. Python will not glue text to a number. Write f"Total: {250}" or "Total: " + str(250).

Choose what information cleaning may remove

"a,,b".split(",") produces ["a", "", "b"]: the blank middle field is information. " a b ".split() produces ["a", "b"]: whitespace runs and edge blanks are deliberately discarded. Use the first behavior for a simple delimited record, the second for command words. Real CSV also needs quote handling; its parser is covered in the CSV project.

Cleaning is not always harmless. .strip() removes whitespace at the ends, not inside; .lower() changes case but does not validate an identifier. Keep the original if its spelling matters. A string is a sequence of Unicode code points, so an accented character plus a combining mark or an emoji sequence can occupy several indices despite looking like one symbol. The ASCII examples here avoid that extra display problem.

Build a parser for " item-17 : ready " that splits only at the first colon, trims both fields and preserves their internal characters. Decide what to report for "item-17:" and "item-17" before writing it. An empty value and a missing separator should remain distinguishable.

Quick practice

What does this print?
print("o'brien".title())
What does this print?
print(len("a b  c".split()))
What does this print?
code = "PNR4521789"
print(code[3:] + code[:3])
broken — fix itTypeError

A booking screen crashes on this line. Make it print the message.


🎯 Your turn

Write receipt_header(restaurant, table), the tidy line at the top of every receipt:

  • receipt_header("cafe python", 12) → "Cafe Python — Table 12"
  • receipt_header("THE GRILL", 8) → "The Grill — Table 8"

Hint: clean the name with restaurant.strip().title(), then build the line with an f-string: f"{...} — Table {table}". That dash is an em dash, —.

Press ▶ Run, try the Live App chips, then ✓ Check. Green means this piece of the app is built.

Your task
Build receipt_header(restaurant, table). It tidies up a venue name and returns the receipt's top line as 'Restaurant — Table N'. Example: receipt_header("cafe python", 12) → "Cafe Python — Table 12".
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — receipt_header(): The header line printed at the top of every receipt.
Scenario A guest scrawls the venue name with odd spacing and caps. The receipt's top line must always read cleanly, like 'Cafe Python — Table 12'.
receipt_header.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
receipt_header(restaurant, table) → strThe tidy header line at the top of the receipt.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.