Skip to content

Module 7 · Strings — topic 4 of 22

Slicing

Extract parts of a string with s[start:stop:step]. Learn default values, negative positions, steps and reversal, and why slicing never raises IndexError.

Beginner 12 min read·Lesson 85 of 306 in Python Programming

Learning objectives

  • Extract substrings with start and stop
  • Use default and negative slice positions
  • Reverse and skip characters with step

Definition

Extract parts of a string with s[start:stop:step]. Learn default values, negative positions, steps and reversal, and why slicing never raises IndexError.

Introduction

Indexing gives one character; slicing gives a range of characters. s[2:5] returns a new string containing the characters at indexes 2, 3 and 4. Like range(), the stop position is excluded.

Why it matters

Slicing extracts structured parts of text: the year from a date, the area code from a phone number, the first ten characters for a preview. It is short, safe and works on every sequence type.

Detailed explanation

A helpful way to picture slicing is to number the gaps between characters instead of the characters themselves. Gap 0 is before the first character and gap len(s) is after the last; text[2:5] cuts at gaps 2 and 5 and keeps what lies between. This picture explains why the stop position is excluded and why the slice length is stop minus start.

s[start:stop] includes start and excludes stop, so its length is stop - start (when both are in range).

Leaving out start means “from the beginning”; leaving out stop means “to the end”. s[:3] is the first three characters, s[3:] everything after them, and s[:] a full copy.

Negative positions count from the end: s[-3:] is the last three characters, s[:-1] everything except the last.

A third value, step, takes every step-th character: s[::2] every second character. A negative step goes backwards: s[::-1] reverses the string.

Slicing never raises IndexError. Positions beyond the ends are clipped: "abc"[1:100] is "bc" and "abc"[5:] is "".

Slices always create new strings; the original is unchanged.

A useful identity: s[:i] + s[i:] == s for any i.

Syntax

Python
part = text[start:stop]
head = text[:n]
tail = text[n:]
every_other = text[::2]
reversed_text = text[::-1]
  • start is included, stop is excluded.
  • Omitted start or stop means the beginning or end.
  • step controls direction and spacing.

Code examples

Basic slices

Python
text = "Programming"
print(text[0:3])
print(text[3:7])
print(text[:4], text[4:])
print(text[-4:])
Output
Pro
gram
Prog ramming
ming

Steps and reversal

Python
text = "Programming"
print(text[::2])
print(text[::-1])
print(text[1:100], repr(text[50:]))
Output
Pormig
gnimmargorP
rogramming ''

More examples

Parsing fixed-format codes

Python
date = "2026-11-22"
year, month, day = date[:4], date[5:7], date[8:]
print(day + "/" + month + "/" + year)
pnr = "PNR8452197ZX"
print("Prefix:", pnr[:3], "Number:", pnr[3:-2], "Suffix:", pnr[-2:])
review = "The course was clear, practical and well paced overall."
preview = review[:30] + ("..." if len(review) > 30 else "")
print(preview)
word = "level"
print(word, "is a palindrome:", word == word[::-1])
Output
22/11/2026
Prefix: PNR Number: 8452197 Suffix: ZX
The course was clear, practica...
level is a palindrome: True

Step-by-step explanation

  • date[:4], date[5:7] and date[8:] pick the year, month and day from fixed positions.
  • pnr[3:-2] takes everything between the 3-letter prefix and the 2-letter suffix.
  • review[:30] creates a preview of the first 30 characters and adds ... when the text is longer.
  • word[::-1] reverses the word; equality with the original means it is a palindrome.

Expected output

Running “Parsing fixed-format codes” prints exactly:

TextOutput
22/11/2026
Prefix: PNR Number: 8452197 Suffix: ZX
The course was clear, practica...
level is a palindrome: True

Practical applications

  • Search results show slices of text as previews.
  • Bank statements and fixed-width files are parsed with slices.
  • Data cleaning removes prefixes and suffixes such as currency symbols with slicing.

Best practices

  • Name the positions of fixed-format fields with constants.
  • Use [::-1] to reverse strings.
  • Prefer methods such as split() when the format has separators.

Common mistakes

Expecting stop to be included

Avoid

text[0:3] # expecting 4 characters

Prefer

text[0:4]

The character at stop is never included.

Reversing with a positive step

Avoid

text[-1:0] # empty

Prefer

text[::-1]

With the default step of 1, a start after the stop gives an empty slice.

Key takeaways

  • s[start:stop:step] extracts a substring; stop is excluded.
  • Omitted values default to the ends; negative values count from the end.
  • Slicing never raises IndexError and always returns a new string.

Try it yourself

  1. 1
    From the string "KA-05-MN-1234", extract the state code and the final number with slices.
  2. 2
    Print a word with its first and last characters removed.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

2 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic