Python Strings Tutorial: Slicing, f-strings and String Methods with Examples
P3.2 Python String Indexing and Slicing Explained
Why. Codes often hide information in fixed places. For example, the first 3 letters of "LON-2026-0042" are the city. Slicing pulls them out.
What. Each character has a position number called an index. Counting starts at 0. Negative numbers count from the end.
text[0]— first charactertext[-1]— last charactertext[0:3]— characters 0, 1, 2 (the end number is not included)text[4:]— from position 4 to the end
| Character | L | O | N | - | 2 | 0 | 2 | 6 |
|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
How to read this table: the top row is each character of "LON-2026"; the bottom row is its index.
How.
Slice a part of text
- Write the text or variable.
- Add square brackets.
- Put start:end inside.
- Remember the end position is left out.
Worked example A — First and last character.
Step 1 — What we do. We take the first and last letter of a ticket ID.
Step 2 — Type and run this code.
ticket = "LON-2026-0042"
print(ticket[0])
print(ticket[-1])
Step 3 — Output you should see.
L
2
Step 4 — What it means. Index 0 is the first character, -1 the last. No counting from the end needed.
Worked example B — Cut the city code and the year.
Step 1 — What we do. The same ticket. We slice the city and the year.
Step 2 — Type and run this code.
ticket = "LON-2026-0042"
print(ticket[0:3])
print(ticket[4:8])
Step 3 — Output you should see.
LON
2026
Step 4 — What it means. [0:3] gives positions 0–2 = "LON". [4:8] gives positions 4–7 = "2026".
Worked example C — Take the end part.
Step 1 — What we do. We need only the running number at the end.
Step 2 — Type and run this code.
ticket = "LON-2026-0042"
print(ticket[-4:])
print(int(ticket[-4:]))
Step 3 — Output you should see.
0042
42
Step 4 — What it means. [-4:] means the last 4 characters. int() turns "0042" into the number 42.
Ravindra Bagale's Tip
Slicing works only when every code has the same shape. If lengths change, use split() instead (next section).
Ravindra Bagale's Tip – मराठी
प्रत्येक code ची रचना सारखी असेल तेव्हाच slicing चालतं. लांबी बदलत असेल तर split() वापरा (पुढचा section).
Ravindra Bagale's Tip – हिंदी
Slicing तभी काम करता है जब हर code की बनावट एक जैसी हो. लंबाई बदलती हो तो split() इस्तेमाल करो (अगला section).