1. First Steps & Data Basics

Strings Deep Dive: Slicing, Formatting & Cleaning Text

Work confidently with text in Python: index and slice characters, understand why strings cannot be mutated in place, clean messy user input, and validate text with built-in methods.

3 min readUpdated 2026-11-29
In This Lesson
  • Pick individual characters and slices from strings using positive and negative indexes
  • Understand why strings are locked (immutable) and why methods return new copies
  • Clean and validate user text with .strip(), .lower(), .replace(), and .isdigit()

Almost everything users type into an app—names, search bars, email addresses, passwords, and file paths—arrives as text (strings). Knowing how to inspect, clean, and check strings cleanly saves hours of frustration.

Strings Are Sequences of Characters

Just like a train made of connected cars, a string is a sequence of individual characters. That means you can grab any character by its position (starting at 0!) or take a slice:

python
word = "Python"

print(word[0])     # 'P' (first character)
print(word[-1])    # 'n' (last character)
print(word[0:3])   # 'Pyt' (positions 0, 1, 2 — stops before 3)
print(len(word))   # 6 (total characters)
Character Indexes in "Python" (Slice [0:3] Highlighted)
0
P
-6
1
y
-5
2
t
-4
3
h
-3
4
o
-2
5
n
-1
Top: positive index (0 to 5)Bottom: negative index (-6 to -1)

Positive indexes count left-to-right (0..5), negative indexes count right-to-left (-6..-1). Slice [0:3] grabs "Pyt" and stops right before index 3.

Bonus Trick: Reversing a String ([::-1])

Adding a third number inside [start:stop:step] sets the step size. A step of -1 walks backward from end to start:

python
print("Python"[::-1])   # "nohtyP"

Why Strings Are "Locked" (Immutable)

If you try to change a single letter directly, Python stops you with a TypeError:

python
name = "cat"
# name[0] = "b"  <-- CRASH! TypeError: 'str' object does not support item assignment

Why? Because in Python, strings are locked once created. Instead of editing an old string, string methods always give you back a brand-new string:

python
name = "cat"
new_name = "b" + name[1:]   # Joins "b" + "at" -> "bat"
print(new_name)             # "bat"
print(name)                 # Still "cat"

Everyday String Methods

Notice how you must save the returned result into a variable (because the original string never changes by itself!):

MethodWhat It DoesExampleResult
.strip()Removes spaces at start & end" hi ".strip()"hi"
.lower() / .upper()Converts letter casing"Py".lower()"py"
.title()Capitalizes each word"alex smith".title()"Alex Smith"
.replace(a, b)Swaps text a for b"hi alex".replace("alex", "maya")"hi maya"
.split(sep)Cuts string into a list"a,b,c".split(",")["a", "b", "c"]
.startswith(x)Checks beginning (True/False)"https://...".startswith("https")True
.isdigit()Checks if every char is 0-9"42".isdigit()True
Forgetting to Save the Result

Writing email.strip().lower() on a line by itself throws away the cleaned copy! Always assign it: email = email.strip().lower()

Predict, Run & Check

Before clicking Run Code, predict in your head what cleaned and is_valid will be!

Python 3Try It Live: Username Cleaner & Check
Output

Click “Run Code” to execute this snippet right in your browser.

Modify Challenge: Change raw_name to " 9alex! " and also check not cleaned[0].isdigit() inside is_valid so usernames starting with a digit are rejected (False).

Quick Checkpoints

Check Your Understanding

Given text = ' Hello ', what does text.strip() followed by print(text) output?

Check Your Understanding

Which expression checks whether code = '12345' contains only digits?