PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » String Slicing and Indexing in Python (With Examples)

String Slicing and Indexing in Python (With Examples)

Updated on: December 4, 2026 | Leave a Comment

Indexing lets you get a single character from a string, and slicing lets you get a whole piece of it. Together, they’re how you grab the first letter of a name, the last four digits of a card number, the file extension of a path, or a reversed copy of a word.

In this tutorial, you’ll learn how Python numbers the characters in a string, how the [start:stop:step] syntax works in every combination, and how to avoid the off-by-one mistakes that confuse beginners.

Key terms used in this article:

  • Index: The position number of a character. Python starts counting at 0.
  • Negative index: A position counted from the end of the string. -1 is the last character.
  • Slice: A part of a string selected with [start:stop:step].
  • Step: How many positions to move between characters. A negative step moves backward.

Table of contents

  • How Python indexes a string
  • Accessing characters with indexing
    • IndexError: string index out of range
    • Looping over indexes
  • Slicing syntax: [start:stop:step]
  • Omitting start and stop
  • Slicing with negative indexes
  • Using a step
  • Negative step: slicing backward
    • Reversing a string
  • Out-of-range slices don’t raise errors
  • Slices create new strings
  • The slice() object
  • Slicing works on all sequences
  • Real-world examples
  • Quick reference
  • Common mistakes
  • Practice exercises
  • Summary

How Python indexes a string

Every character in a string has two index numbers: a positive index counted from the left starting at 0, and a negative index counted from the right starting at -1.

String:          P   Y   N   A   T   I   V   E
Positive index:  0   1   2   3   4   5   6   7
Negative index: -8  -7  -6  -5  -4  -3  -2  -1

The last positive index is always len(string) - 1.

Accessing characters with indexing

Use square brackets with an index to get a single character:

site = "PYNATIVE"

print(site[0])    # first character
print(site[1])
print(site[7])    # last character
print(site[-1])   # last character, the easy way
print(site[-3])
print(site[len(site) - 1])Code language: Python (python)

Output:

P
Y
E
E
I
E

The result is always a string of length 1, because Python has no separate character type.

IndexError: string index out of range

An index outside the string raises an IndexError:

word = "code"
try:
    print(word[4])
except IndexError as error:
    print("Error:", error)Code language: Python (python)

Output:

Error: string index out of range

word has 4 characters, so the valid indexes are 0 to 3 (or -1 to -4). This is the most common indexing mistake.

Looping over indexes

When you need both the position and the character, use enumerate() instead of range(len(...)):

word = "loop"
for index, ch in enumerate(word):
    print(index, ch)Code language: Python (python)

Output:

0 l
1 o
2 o
3 p

Slicing syntax: [start:stop:step]

A slice returns a new string containing part of the original:

string[start:stop:step]Code language: Python (python)
  • start: The index where the slice begins. It’s included. Default: the beginning.
  • stop: The index where the slice ends. It’s excluded. Default: the end.
  • step: How many characters to move each time. Default: 1.

The rule “start is included, stop is excluded” means s[a:b] contains exactly b - a characters (when 0 <= a <= b <= len(s)).

text = "Python Slicing"

print(text[0:6])    # characters 0 to 5
print(text[7:14])
print(text[2:5])
print(len(text[2:5]))Code language: Python (python)

Output:

Python
Slicing
tho
3

A helpful way to picture it: indexes point between characters, and a slice cuts at those points.

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

"Python"[1:4] cuts at positions 1 and 4, giving "yth".

Omitting start and stop

Leave out start to slice from the beginning, and leave out stop to slice to the end:

text = "Hello, World"

print(text[:5])   # first 5 characters
print(text[7:])   # from index 7 to the end
print(text[:])    # the whole string (a copy)Code language: Python (python)

Output:

Hello
World
Hello, World

s[:n] + s[n:] always gives back the original string s, for any n. This makes it easy to split a string at a position:

text = "Hello, World"
n = 5
print(text[:n] + text[n:] == text)
print(repr(text[:n]), repr(text[n:]))Code language: Python (python)

Output:

True
'Hello' ', World'

Slicing with negative indexes

Negative indexes are perfect for taking characters from the end without knowing the length:

filename = "summary_report.pdf"

print(filename[-3:])    # last 3 characters
print(filename[:-4])    # everything except the last 4
print(filename[-10:-4])Code language: Python (python)

Output:

pdf
summary_report
report
SliceMeaning
s[:3]First 3 characters
s[-3:]Last 3 characters
s[3:]Everything except the first 3
s[:-3]Everything except the last 3
s[1:-1]Everything except the first and last character
s = "abcdefgh"
print(s[:3], s[-3:], s[3:], s[:-3], s[1:-1])Code language: Python (python)

Output:

abc fgh defgh abcde bcdefg

Using a step

The third value, step, skips characters:

alphabet = "abcdefghijklmnopqrstuvwxyz"

print(alphabet[::2])     # every 2nd character
print(alphabet[1::2])    # every 2nd, starting at index 1
print(alphabet[::5])     # every 5th character
print(alphabet[2:12:3])  # from 2 to 11, every 3rdCode language: Python (python)

Output:

acegikmoqsuwy
bdfhjlnprtvxz
afkpuz
cfil

A step of 0 raises ValueError: slice step cannot be zero.

Negative step: slicing backward

With a negative step, Python walks from right to left. The defaults flip too: start defaults to the end and stop defaults to the beginning.

text = "Python"

print(text[::-1])     # reversed
print(text[::-2])     # every 2nd character, backward
print(text[4:1:-1])   # from index 4 down to index 2
print(text[-1:-4:-1]) # last three, backwardCode language: Python (python)

Output:

nohtyP
nhy
oht
noh

With a negative step, start must be greater than stop, or the slice is empty:

text = "Python"
print(repr(text[1:4:-1]))  # empty: can't go backward from 1 to 4
print(repr(text[4:1:-1]))Code language: Python (python)

Output:

''
'oht'

Reversing a string

[::-1] is the standard way to reverse a string:

word = "racecar"
name = "Jessa"

print(name[::-1])
print(word == word[::-1])  # palindrome checkCode language: Python (python)

Output:

asseJ
True

Out-of-range slices don’t raise errors

Unlike indexing, slicing is forgiving. If the indexes go past the ends of the string, Python just stops at the boundary:

text = "short"

print(text[0:100])
print(repr(text[10:20]))   # empty string
print(text[-100:3])Code language: Python (python)

Output:

short
''
sho

This is convenient: text[:10] safely gives “up to 10 characters”, even for shorter strings.

Slices create new strings

Strings are immutable, so a slice always creates a new string. You can’t assign to a slice of a string, but you can build a new string from slices:

word = "Python"
try:
    word[0:2] = "Ja"
except TypeError as error:
    print("Error:", error)

new_word = "Ja" + word[2:]
print(new_word)

# Insert text at a position
sentence = "I love Python"
position = 7
print(sentence[:position] + "learning " + sentence[position:])

# Remove the character at index 2
s = "abcdef"
print(s[:2] + s[3:])Code language: Python (python)

Output:

Error: 'str' object does not support item assignment
Jathon
I love learning Python
abdef

The slice() object

The built-in slice() function creates a reusable slice. text[slice(start, stop, step)] is the same as text[start:stop:step]:

record = "2026-12-04|Jessa|London"

year = slice(0, 4)
month = slice(5, 7)
day = slice(8, 10)

print(record[year], record[month], record[day])

last_three = slice(-3, None)
print("Python"[last_three])Code language: Python (python)

Output:

2026 12 04
hon

Named slices make code that parses fixed-width text much easier to read.

Slicing works on all sequences

Everything in this tutorial also works on lists, tuples, range objects, and bytes:

numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
print(numbers[::-1])
print((1, 2, 3, 4)[::2])
print(range(10)[2:8:2])Code language: Python (python)

Output:

[20, 30, 40]
[50, 40, 30, 20, 10]
(1, 3)
range(2, 8, 2)

The one difference: lists are mutable, so you can assign to a list slice, such as numbers[1:3] = [0, 0]. See Python Lists.

Real-world examples

Example 1: Get a file extension and name

filename = "vacation_photo.jpeg"
dot = filename.rfind(".")
print(filename[:dot])
print(filename[dot + 1:])Code language: Python (python)

Output:

vacation_photo
jpeg

Example 2: Mask an email address

email = "jessa.doe@example.com"
at = email.index("@")
masked = email[0] + "*" * (at - 1) + email[at:]
print(masked)Code language: Python (python)

Output:

j********@example.com

Example 3: Show the last 4 digits of an account number

account = "123456789012"
print("*" * (len(account) - 4) + account[-4:])Code language: Python (python)

Output:

********9012

Example 4: Truncate long text for a preview

def preview(text, limit=20):
    return text if len(text) <= limit else text[:limit - 3] + "..."

print(preview("Short title"))
print(preview("A very long title that needs to be cut"))Code language: Python (python)

Output:

Short title
A very long title...

Example 5: Rotate a string

s = "abcdef"
k = 2
print(s[k:] + s[:k])    # rotate left
print(s[-k:] + s[:-k])  # rotate rightCode language: Python (python)

Output:

cdefab
efabcd

Example 6: Split a string into fixed-size chunks

code = "ABCDEFGHIJKL"
chunks = [code[i:i + 4] for i in range(0, len(code), 4)]
print(chunks)
print("-".join(chunks))Code language: Python (python)

Output:

['ABCD', 'EFGH', 'IJKL']
ABCD-EFGH-IJKL

Quick reference

ExpressionResult for s = "Python"Meaning
s[0]'P'First character
s[-1]'n'Last character
s[1:4]'yth'Index 1 up to (not including) 4
s[:2]'Py'First 2 characters
s[2:]'thon'From index 2 to the end
s[-2:]'on'Last 2 characters
s[:-2]'Pyth'All except the last 2
s[::2]'Pto'Every 2nd character
s[::-1]'nohtyP'Reversed
s[:]'Python'Full copy

Common mistakes

  • Expecting the stop index to be included. "Python"[0:3] is "Pyt", not "Pyth".
  • Using len(s) as an index. The last valid index is len(s) - 1. Use s[-1] instead.
  • Getting an empty result with a negative step. With step < 0, start must be to the right of stop.
  • Trying to change a string through a slice. Build a new string instead.
  • Forgetting that indexes start at 0. The third character is s[2].

Practice exercises

Exercise 1: Print the first, middle, and last character of an odd-length string.

word = "Python3"
middle = len(word) // 2
print(word[0], word[middle], word[-1])Code language: Python (python)

Output:

P h 3

Exercise 2: Swap the first two and last two characters of a string.

s = "abcdefg"
print(s[-2:] + s[2:-2] + s[:2])Code language: Python (python)

Output:

fgcdeab

Exercise 3: Print every character at an even index, then every character at an odd index.

s = "PYnative"
print(s[::2])
print(s[1::2])Code language: Python (python)

Output:

Pntv
Yaie

Exercise 4: Check whether the second half of a string is the reverse of the first half.

def mirrored(s):
    half = len(s) // 2
    return s[:half] == s[-half:][::-1] if half else True

print(mirrored("abccba"))
print(mirrored("abcabc"))Code language: Python (python)

Output:

True
False

Summary

  • Indexes start at 0 from the left and -1 from the right. s[i] returns one character.
  • An index outside the string raises IndexError, but slices outside the string just return what’s available.
  • s[start:stop:step] includes start, excludes stop, and moves by step.
  • Leave out start or stop to slice from the beginning or to the end. s[:] makes a copy.
  • Negative indexes count from the end: s[-3:] gives the last 3 characters.
  • A negative step slices backward. s[::-1] reverses a string.
  • Slices create new strings. Use slice() objects to name and reuse slices.

Also, See:

  • Strings in Python: A Complete Guide
  • Python String Methods
  • Python Lists
  • Python String Exercises

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com