These are the notes for Python episode 5. Names, phone numbers, messages and bills: most real-world data is text. You will learn how Python numbers every character from 0, the IndexError you get when you go too far, negative indexes, why strings can never be changed in place, cutting out pieces with slicing (and reversing a string), cleaning messy input with strip() and lower(), why name.strip() on its own does nothing, the everyday methods find, count, replace, split and join, and f-strings for neat bills. Every example below runs as-is in the SyntaxPilot compiler (type the input in the input box before you press Run), with its real output from Python 3.13.
The problem: Raju's loyalty cards
Raju starts a loyalty card for his chai stall. Every card shows the customer's initial in big letters: Priya gets a P. He has 500 customers, and typing every initial by hand is slow and full of mistakes.
The names are already in his program as strings (a string, type str, is a piece of text written inside quotes, like "Priya"). Can Python pick out the first letter by itself? To do that, Python needs a way to point at one character (a character is a single letter, digit, space or symbol).
Indexing: a string is a row of numbered seats
Think of a string as a row of seats in a bus:
| In a bus | In Python |
|---|---|
| A row of seats, one passenger each | "Priya": one character per seat |
| Every seat has a number, starting at 0 | name[0] is "P" |
| How many seats there are | len(name) is 5, so the seats are 0 to 4 |
The seat number is called an index: write the string (or its variable), then the index in square brackets, name[0]. Python is zero-based: it counts from 0, not 1. len() (short for length) counts the characters, so the last index is always len(name) - 1.
name = "Priya"
print(name[0])
print(name[4])
print(len(name))
P
a
5
The initial in one line: name[0]. Now Raju's loyalty cards print themselves.
The index diagram for "Priya"
| Character | P |
r |
i |
y |
a |
|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 |
| Negative index | -5 | -4 | -3 | -2 | -1 |
IndexError: asking for a seat that doesn't exist
If we count like humans, five letters means the last one is seat 5, right?
name = "Priya"
print(name[5])
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(name[5])
~~~~^^^
IndexError: string index out of range
There is no seat 5. The seats go from 0 to 4, so asking for seat 5 is like asking for a passenger in a seat the bus doesn't have. IndexError means "that index is outside the string". Out of range means "not between the first and last index".
Negative indexes: counting from the end
To get the last letter without counting, use a negative index: -1 is the last seat, -2 the second last, all the way to -5, the first.
name = "Priya"
print(name[-1])
print(name[-5])
a
P
name[-1] always gives the last character, whatever the length. Going too far backwards (name[-6]) is also an IndexError.
Strings can't be changed (immutable)
Next problem: a name was typed in small letters, priya. We know seat 0 holds the small p, so let's put a capital P in seat 0:
name = "priya"
name[0] = "P"
Traceback (most recent call last):
File "main.py", line 2, in <module>
name[0] = "P"
~~~~^^^
TypeError: 'str' object does not support item assignment
Item assignment means putting something into one seat (name[0] = ...). Strings don't allow it, because strings in Python are immutable: once made, they can never change.
Think of a printed receipt: you can't rub out one letter on it, but you can print a new receipt. So we build a new string and store it back in the same variable:
name = "priya"
name = "P" + name[1:]
print(name)
Priya
"P" + name[1:] joins a capital P with everything from seat 1 onwards. Joining strings with + is called concatenation. That name[1:] is called a slice, and it's exactly what we need next.
Slicing: cut out a piece
One letter is not enough any more. A train ticket's PNR number has ten digits and the first three mean something (the reservation zone). A date like 28-10-2026 where we only want the year. Picking letters one at a time and joining them is painful: we need scissors that cut from this seat to that seat.
That is slicing: text[start:stop].
| Rule | Example with pnr = "4521876309" |
|---|---|
| start is included, stop is NOT | pnr[0:3] → "452" (seats 0, 1, 2) |
| Leave out start = from the beginning | pnr[:3] → "452" |
| Leave out stop = to the end | pnr[7:] → "309" |
stop - start = how many characters you get |
pnr[3:7] → 4 characters |
pnr = "4521876309"
print(pnr[0:3])
print(pnr[3:7])
print(pnr[:3], pnr[7:])
print(pnr[-4:])
452
1876
452 309
6309
pnr[-4:] starts four seats before the end and goes to the end: the last four digits, just like a bank shows only the last four digits of your card.
Now the date:
date = "28-10-2026"
print(date[0:2], date[3:5], date[6:])
print(date[6:100])
28 10 2026
2026
No error for 100! An index past the end crashes, but a slice past the end just stops at the end.
The step: reversing and skipping
A slice can take a third number, the step: text[start:stop:step]. The step says how many seats to jump each time. A step of -1 walks backwards, so [::-1] reverses the string.
word = "level"
print(word[::-1])
print(word == word[::-1])
print("SyntaxPilot"[::2])
level
True
SnaPlt
"level"backwards is"level", so the comparison with==(is equal to) isTrue. A word that reads the same both ways is a palindrome.word == word[::-1]is a classic interview one-liner.- A step of 2 takes every second letter: S, n, a, P, l, t.
Cleaning messy input: string methods
Raju's app saves the customer name ravi, all small letters. But Ravi types on his phone: the keyboard adds a capital R, and he adds spaces before and after.
name = input("Name: ")
print(name == "ravi")
Input: Ravi (two spaces, Ravi, one space)
Name: False
(In the SyntaxPilot compiler the typed input isn't echoed, so the prompt and the output appear on one line.)
To you it's the same person; to Python every character counts, and " Ravi " is not "ravi".
Strings come with built-in tools called methods. A method is a function that belongs to a value; you call it with a dot after the string and brackets at the end: name.strip().
| Method | What it gives back | Example |
|---|---|---|
strip() |
the text without spaces (and tabs/newlines) at both ends | " Ravi ".strip() → "Ravi" |
lower() |
all small letters | "Ravi".lower() → "ravi" |
upper() |
all capital letters | "ravi".upper() → "RAVI" |
title() |
first letter of each word capital | "priya sharma".title() → "Priya Sharma" |
Why name.strip() alone changes nothing
name = input("Name: ")
name.strip()
name.lower()
print(name == "ravi")
Input: Ravi
Name: False
Still False! We called both methods and nothing changed. Remember: strings are immutable. strip() and lower() can't change name. They make a new, cleaned string and hand it back. What a method hands back is called its return value. We threw it away. We have to catch it:
name = input("Name: ")
name = name.strip().lower()
print(name == "ravi")
print(name.upper(), name.title())
Input: Ravi
Name: True
RAVI Ravi
name.strip().lower() is chaining: methods joined with dots run left to right. strip() returns "Ravi", then .lower() runs on that and returns "ravi".
name = name.strip().lower()fixes almost every messy text input.
Real-life example: photocopier buttons
| At the copy shop | In Python |
|---|---|
| Your original page never changes | name, the original string |
| Press "enlarge": you get a new copy | name.upper() returns a new string |
| Take the copy, or it's left in the tray | name = name.upper() stores the result |
find, count, replace, in
msg = "chai is hot, chai is sweet"
print(msg.count("chai"))
print(msg.find("hot"), msg.find("cold"))
print(msg.replace("chai", "coffee"))
print("hot" in msg, msg.startswith("chai"))
2
8 -1
coffee is hot, coffee is sweet
True True
count(x)counts how many timesxappears: 2.find(x)gives the index wherexstarts ("hot"starts at seat 8). Ifxisn't there, it gives-1, meaning "not found".replace(old, new)returns a new string with everyoldswapped fornew.msgitself is unchanged.- The
inoperator asks "is this text inside that text?" and givesTrueorFalse.startswith(x)asks whether the string begins withx. These True/False answers are exactly whatifstatements use (next episode).
split and join: cut and glue
Raju's order arrives as one string with commas: chai,samosa,vada pav.
items = "chai,samosa,vada pav"
parts = items.split(",")
print(parts)
print(" | ".join(parts))
['chai', 'samosa', 'vada pav']
chai | samosa | vada pav
split(",")cuts the string at every comma and gives a list: a collection of values inside square brackets, here three strings. (Lists are covered properly in episode 10.)split()with nothing in the brackets cuts at any run of spaces." | ".join(parts)glues the pieces back into one string, with" | "between them. Note the shape: the glue comes first, then.join(pieces).
Split cuts, join glues.
f-strings: mixing text and numbers
Raju wants bill lines like Chai x 3 = Rs 37.5. One way we know: join pieces with +.
item = "Chai"
price = 12.5
cups = 3
print("Item: " + item + ", cups: " + cups)
Traceback (most recent call last):
File "main.py", line 4, in <module>
print("Item: " + item + ", cups: " + cups)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "int") to str
Our old friend from episode 3: + can't join text and a number. Wrapping every number in str() works, but with many values it becomes a mess of plus signs and quotes.
The fix is an f-string: put the letter f just before the opening quote. Inside the text, curly brackets {} hold any variable, or even a calculation.
item = "Chai"
price = 12.5
cups = 3
print(f"{item} x {cups} = Rs {price * cups}")
Chai x 3 = Rs 37.5
No +, no str(), and price * cups was calculated right inside the brackets. The f stands for formatted.
The most common mistake: forgetting the f
In the video we add one more line to the same program, without the f:
print("{item} x {cups}")
The program now prints Chai x 3 = Rs 37.5 and then {item} x {cups}. Without the f, the curly brackets are just plain text. No error, just an ugly bill.
Format specifiers: decimals and alignment
After a colon inside the curly brackets you can add a format specifier: a short code that says how to show the value.
total = 37.5
print(f"Total: {total:.2f}")
print(f"{'Chai':<8}|{12:>6.2f}")
print(f"{'Samosa':<8}|{15:>6.2f}")
Total: 37.50
Chai | 12.00
Samosa | 15.00
| Specifier | Meaning | Result |
|---|---|---|
:.2f |
a decimal number with exactly 2 decimal places | 37.5 → 37.50 |
:<8 |
left-align in a space 8 characters wide | Chai |
:>6.2f |
right-align in 6 characters, 2 decimals | 12.00 |
The prices sit in a straight column: that's a real receipt. (Inside a double-quoted f-string, write text values with single quotes, as in 'Chai'. Using the same quote type inside only works from Python 3.12.)
Common mistakes (and the real error messages)
| Mistake | Error | Why | Fix |
|---|---|---|---|
name[5] on "Priya" |
IndexError: string index out of range |
indexes go 0 to len - 1 |
name[4] or name[-1] |
name[0] = "P" |
TypeError: 'str' object does not support item assignment |
strings are immutable | name = "P" + name[1:] |
name.strip() on its own line |
no error: name is unchanged |
methods return a new string | name = name.strip() |
"Cups: " + cups (cups is an int) |
TypeError: can only concatenate str (not "int") to str |
text + number | f"Cups: {cups}" |
print("{item}") |
no error: prints {item} |
forgot the f |
print(f"{item}") |
name[1.5] |
TypeError: string indices must be integers, not 'float' |
an index must be a whole number | name[1] |
"Priya".index("z") |
ValueError: substring not found |
index() crashes when missing |
find() returns -1 instead |
print(name.upper) |
no error: prints <built-in method upper of str object at 0x...> |
forgot the () so the method never ran |
name.upper() |
first, last = "Priya".split() |
ValueError: not enough values to unpack (expected 2, got 1) |
only one word to split | check the input has two words |
Mini project: username and email generator
Raju's app needs a username and an email for every new customer, made from their full name.
# Mini project: username generator
full = input("Full name: ")
full = full.strip().title()
first, last = full.split()
print(f"Hello, {first}!")
print(f"Initials: {first[0]}{last[0]}")
print(f"Username: {first.lower()}.{last.lower()}")
print(f"Email: {first[0].lower()}{last.lower()}@syntaxpilot.in")
Input (messy on purpose: spaces, small letters, extra spaces in the middle): priya sharma
Full name: Hello, Priya!
Initials: PS
Username: priya.sharma
Email: psharma@syntaxpilot.in
strip()removed the outer spaces andtitle()madePriya Sharma.split()with no argument ignores the extra spaces in the middle, giving two pieces, which we catch infirstandlast.first[0]andlast[0]are the initials;.lower()inside the f-string builds the username and email.- With three names,
first, last = ...fails withValueError: too many values to unpack (expected 2).
Practice
- Homework: ask for a word, print it backwards, and check whether it is a palindrome (ignore capitals and spaces at the ends).
Solution
word = input("Word: ").strip().lower()
print(word[::-1])
print(word == word[::-1])
Input Madam → Word: madam then True.
- Homework: mask a phone number so only the last 4 digits show:
9876543210→******3210.
Solution
phone = input("Phone: ").strip()
masked = "*" * (len(phone) - 4) + phone[-4:]
print(masked)
Input 9876543210 → Phone: ******3210
"*" * 6 repeats the star six times (string times number repeats, as in episode 3).
- Homework: count how many times the letter
aappears in a sentence, capital or small.
Solution
sentence = input("Sentence: ")
print(sentence.lower().count("a"))
Input A banana a day → Sentence: 6
lower() first, so the capital A is counted too.
- Homework: print a 3-item bill with the prices lined up and a total.
Solution
chai, samosa, pav = 12, 15, 20.5
total = chai + samosa + pav
print(f"{'Chai':<10}|{chai:>7.2f}")
print(f"{'Samosa':<10}|{samosa:>7.2f}")
print(f"{'Vada Pav':<10}|{pav:>7.2f}")
print("-" * 18)
print(f"{'Total':<10}|{total:>7.2f}")
Chai | 12.00
Samosa | 15.00
Vada Pav | 20.50
------------------
Total | 47.50
- Split the date
28-10-2026into day, month and year, and print it as28/10/2026.
Solution
date = "28-10-2026"
day, month, year = date.split("-")
print("Year:", year)
print(f"{day}/{month}/{year}")
Output: Year: 2026 then 28/10/2026.
Quick quiz
What does this print?
s = "SyntaxPilot"
print(s[-5:], s[6:-1])
A) Pilot Pilo B) Pilot Pilot C) ilot Pilo D) Error
Answer
A) Pilot Pilo. s[-5:] starts 5 seats from the end and goes to the end: Pilot. s[6:-1] starts at seat 6 (P) and stops before the last seat: Pilo.
Interview questions
- Why are strings immutable in Python? It makes them safe to share: many variables can point to the same string without one changing it behind another's back. It also lets Python cache a string's hash, so strings work as dictionary keys and set items, and lets it reuse identical small strings to save memory. Every "change" creates a new string.
- What is the difference between
find()andindex()? Both return the index where the substring starts. When it's missing,find()returns-1whileindex()raisesValueError: substring not found. - What is the difference between
==andisfor strings?==compares the text (value);ischecks whether both names point to the same object in memory.a = "hi"andb = "".join(["h", "i"])givea == basTruebuta is basFalse. Always use==to compare strings. - How do you reverse a string? How do you check a palindrome?
s[::-1]; a palindrome check iss == s[::-1](usually afters.strip().lower()). - Why does
s[10]raise an error on a short string buts[2:100]doesn't? Indexing asks for one exact seat, which must exist. Slicing clips the start and stop to the string's length, so it just stops at the end. - What's the difference between
split()andsplit(" ")?split()splits on any run of whitespace and ignores spaces at the ends;split(" ")splits on every single space, so double spaces give empty strings''.
Glossary
| Term | Meaning | Example |
|---|---|---|
String (str) |
Text inside quotes | "Priya" |
| Character | One letter, digit, space or symbol in a string | "P" |
| Index | The seat number of a character | name[0] |
| Zero-based | Counting starts at 0, not 1 | first character is [0] |
| Negative index | Counting from the end; -1 is the last |
name[-1] → "a" |
len() |
Number of characters in a string | len("Priya") → 5 |
IndexError |
You asked for an index that doesn't exist | "Priya"[5] |
| Immutable | Can never be changed after it is made | strings |
| Item assignment | Putting a value into one position with [ ] = |
name[0] = "P" (not allowed) |
TypeError |
An operation on types that don't fit | "Cups: " + 3 |
| Concatenation | Joining strings with + |
"P" + "riya" |
| Slice | A piece cut out with [start:stop]; stop not included |
pnr[0:3] → "452" |
| Step | Third slice number: how many seats to jump | s[::2], s[::-1] |
| Palindrome | Reads the same forwards and backwards | "level", "madam" |
== |
Checks whether two values are equal | "ravi" == "ravi" → True |
| Method | A function that belongs to a value, called with a dot | name.upper() |
| Return value | What a method or function hands back | "Ravi".lower() returns "ravi" |
| Chaining | Calling methods one after another with dots | name.strip().lower() |
strip() |
Removes spaces, tabs and newlines from both ends | " Ravi ".strip() → "Ravi" |
lower() / upper() |
All small / all capital letters | "Ravi".upper() → "RAVI" |
title() |
Capitalises the first letter of each word | "priya sharma".title() |
find() |
Index where a substring starts, or -1 if missing |
msg.find("hot") → 8 |
index() |
Like find(), but raises ValueError if missing |
"Priya".index("i") → 2 |
count() |
How many times a substring appears | msg.count("chai") → 2 |
replace() |
New string with old text swapped for new | msg.replace("chai", "coffee") |
startswith() |
Does the string begin with this text? | msg.startswith("chai") → True |
split() |
Cuts a string into a list of pieces | "a,b".split(",") → ['a', 'b'] |
join() |
Glues a list of strings into one, with glue between | "-".join(["a", "b"]) → "a-b" |
| List | A collection of values in square brackets (episode 10) | ['chai', 'samosa'] |
| Substring | A smaller piece of text inside a string | "hot" in "chai is hot" |
in operator |
Checks if text is inside other text; gives True/False | "hot" in msg |
| f-string | A string with f before the quote; {} holds values |
f"Hi {name}" |
| Format specifier | Code after : inside {} that controls display: .2f = two decimals, <8 / >6 = align left / right in a width |
{total:.2f}, {x:<8} |
| Unpacking | Catching several values into several variables | first, last = full.split() |
Summary
- A string is a row of numbered seats:
s[0]is the first character,s[-1]the last, andlen(s) - 1the last index. - An index past the end gives
IndexError: string index out of range; a slice past the end just stops at the end. - Strings are immutable:
s[0] = "P"is aTypeError. Build a new string instead:s = "P" + s[1:]. - Slices:
s[start:stop:step], start included, stop excluded;s[::-1]reverses, ands == s[::-1]checks a palindrome. - Methods (
strip,lower,upper,title,replace...) return a new string: always store it,name = name.strip().lower(). find(gives-1if missing),count,in,startswith;splitcuts into a list,joinglues back.- f-strings
f"{item} x {cups}"mix text and values without+orstr();{total:.2f}gives two decimals,:<8and:>6line up columns. Don't forget thef.
Next episode: if, elif, else.