Learn Without Walls
← Lesson 1 Lesson 2 of 4 Lesson 3 →

Lesson 7.2: String Slicing

By the end of this lesson, you will be able to:

Strings Are Sequences

Connection to Lists: Strings and lists are both sequences in Python. This means everything you learned about list indexing and slicing works exactly the same way with strings!
word = "Python"
#        P  y  t  h  o  n
#        0  1  2  3  4  5
#       -6 -5 -4 -3 -2 -1

print(word[0])     # First character
print(word[-1])    # Last character
print(len(word))    # Length
P n 6

The key difference: strings are immutable, so you cannot change individual characters. word[0] = "J" would cause an error.

Basic String Slicing

Use string[start:stop] to extract a substring. Just like lists, stop is exclusive.

text = "Hello, World!"

print(text[0:5])    # First 5 characters
print(text[7:12])   # "World"
print(text[:5])     # From start to index 5
print(text[7:])     # From index 7 to end
Hello World Hello World!

Extracting Parts of Data

# Extract area code from phone number
phone = "(555) 123-4567"
area_code = phone[1:4]
print("Area code:", area_code)

# Extract file extension
filename = "document.pdf"
extension = filename[-3:]
print("Extension:", extension)

# Extract date parts
date = "2024-03-15"
year = date[:4]
month = date[5:7]
day = date[8:]
print(f"Year: {year}, Month: {month}, Day: {day}")
Area code: 555 Extension: pdf Year: 2024, Month: 03, Day: 15

Negative Indexing in Slices

text = "Programming"

# Last 4 characters
print(text[-4:])

# Everything except first and last
print(text[1:-1])

# Everything except last 3
print(text[:-3])
ming rogrammin Programm

The Step Parameter

The third value [start:stop:step] controls how many characters to skip.

text = "abcdefghij"

# Every other character
print(text[::2])

# Every third character
print(text[::3])

# Every other character from index 1 to 8
print(text[1:8:2])
acegi adgj bdfh

Reversing Strings

Just like with lists, using a step of -1 reverses the string.

word = "Python"
print(word[::-1])

# Check if a word is a palindrome
def is_palindrome(text):
    text = text.lower()
    return text == text[::-1]

print(is_palindrome("racecar"))
print(is_palindrome("hello"))
print(is_palindrome("Madam"))
nohtyP True False True

Try It Yourself

Write a program that takes a word and checks if it reads the same forwards and backwards (a palindrome). Test it with "level", "python", and "kayak".

Combining Slicing with Methods

You can chain slicing with string methods for powerful text processing.

email = "  USER@EXAMPLE.COM  "

# Clean up and extract the domain
clean = email.strip().lower()
domain = clean[clean.index("@") + 1:]
print(f"Clean email: {clean}")
print(f"Domain: {domain}")
Clean email: user@example.com Domain: example.com

Practical Example: Formatting Names

full_name = "john michael smith"

# Get first initial and last name
first_initial = full_name[0].upper()
last_name = full_name.split()[-1].title()
print(f"{first_initial}. {last_name}")
J. Smith

Check Your Understanding

Given: text = "Introduction"

  1. What does text[0:5] return?
  2. What does text[-4:] return?
  3. What does text[::-1] return?
  4. How would you get every other character?
  1. "Intro"
  2. "tion"
  3. "noitcudortnI"
  4. text[::2] which gives "Itoutin"

Key Takeaways