ZetCode

Python string slicing

last modified November 19, 2026 Python 3.15

In this article we show how to index and slice strings in Python.

A Python string is a sequence of characters, more precisely of Unicode code points. Each character has an index, starting at zero. Negative indexes count from the end: -1 is the last character.

 f   a   l   c   o   n
 0   1   2   3   4   5
-6  -5  -4  -3  -2  -1

A slice s[start:end:step] selects a part of the string. Slicing works the same way for lists and other sequences; see Python list slice.

Indexing

Square brackets with a single index return one character.

indexing.py
word = 'falcon'

print(word[0])
print(word[1])
print(word[-1])
print(word[-2])
print(word[len(word) - 1])
print(type(word[0]), len(word[0]))

Python has no separate character type. An indexed character is a string of length one. The index -1 is a shorter way of writing len(word) - 1.

$ python indexing.py
f
a
n
o
n
<class 'str'> 1

Index out of range

An index must point inside the string.

index_error.py
word = 'falcon'

print(word[5])
print(word[6])

The word has six characters with indexes 0 to 5. Index 6 raises an IndexError.

$ python index_error.py
n
Traceback (most recent call last):
  File "/home/user/python/index_error.py", line 4, in <module>
    print(word[6])
          ~~~~^^^
IndexError: string index out of range

Basic slices

A slice s[start:end] returns the characters from start up to, but not including, end.

slice_basic.py
word = 'falcon'

print(word[0:3])
print(word[1:4])
print(word[3:6])
print(word[2:2])
print(word[0:3] + word[3:6])

The length of a slice is end - start. A slice with equal bounds is empty. Because the end is excluded, two slices that share a bound fit together without a gap or an overlap.

$ python slice_basic.py
fal
alc
con

falcon

Omitted bounds and negative indexes

An omitted start means the beginning of the string; an omitted end means its end. Both bounds can be negative.

slice_omit.py
url = 'https://example.com/docs'

print(url[:5])
print(url[8:])
print(url[-4:])
print(url[:-5])
print(url[:])

url[:5] takes the first five characters and url[8:] everything from index 8. url[-4:] takes the last four characters and url[:-5] all but the last five. url[:] is the whole string; for an immutable string, Python returns the same object rather than a copy.

$ python slice_omit.py
https
example.com/docs
docs
https://example.com
https://example.com/docs

Slices never raise IndexError

Unlike indexes, slice bounds outside the string are clipped to its length.

slice_range.py
word = 'falcon'

print(repr(word[2:100]))
print(repr(word[10:]))
print(repr(word[-100:3]))
print(repr(word[4:2]))

code = 'SK'
print(code[0], repr(code[2:3]))

A slice beyond the end is empty, and a start greater than the end gives an empty string too. The last line shows the difference between code[2], which would raise an error, and code[2:3], which returns an empty string. This makes slices convenient for taking at most n characters.

$ python slice_range.py
'lcon'
''
'fal'
''
S ''

The step

The third slice value is the step. A step of 2 takes every second character.

slice_step.py
letters = 'abcdefghij'

print(letters[::2])
print(letters[1::2])
print(letters[::3])
print(letters[1:8:3])

number = '79927398713'
print(number[-1::-2])
print(number[-2::-2])

letters[::2] takes the characters at even indexes and letters[1::2] those at odd indexes. In the last two lines we split a card number into the two groups of digits used by the Luhn checksum, counted from the right.

$ python slice_step.py
acegi
bdfhj
adgj
beh
379797
18329

Negative step and reversing

A negative step walks the string backwards. With omitted bounds, s[::-1] returns the reversed string.

reverse.py
word = 'falcon'

print(word[::-1])
print(word[4:1:-1])
print(word[-1:-4:-1])
print(word[:2:-1])

for w in ['level', 'falcon', 'Racecar', 'Was it a car or a cat I saw']:
    s = ''.join(c for c in w.casefold() if c.isalnum())
    print(f'{w!r:31} palindrome={s == s[::-1]}')

With a negative step the start must be to the right of the end: word[4:1:-1] takes indexes 4, 3, and 2. A palindrome reads the same in both directions; we drop punctuation and spaces and casefold the text before comparing it with its reverse.

$ python reverse.py
noclaf
ocl
noc
noc
'level'                         palindrome=True
'falcon'                        palindrome=False
'Racecar'                       palindrome=True
'Was it a car or a cat I saw'   palindrome=True

Strings are immutable

We cannot assign to an index or a slice of a string. To change a character, we build a new string from slices.

immutable.py
word = 'falcon'

try:
    word[0] = 'F'
except TypeError as e:
    print(f'error: {e}')

word2 = 'F' + word[1:]
print(word2)

pos = 3
word3 = word[:pos] + 'X' + word[pos + 1:]
print(word3)
print(word)

The assignment raises a TypeError. The expression word[:pos] + 'X' + word[pos + 1:] replaces the character at pos in a new string. The original string is unchanged.

$ python immutable.py
error: 'str' object does not support item assignment
Falcon
falXon
falcon

Rotating a string

Two slices glued in the opposite order rotate a string.

rotate.py
def rotate(s, n):
    if not s:
        return s
    n %= len(s)
    return s[n:] + s[:n]


word = 'falcon'

for n in [1, 2, -1, 6, 8]:
    print(f'{n:3} {rotate(word, n)}')


def is_rotation(a, b):
    return len(a) == len(b) and b in a + a


print(is_rotation('falcon', 'confal'))
print(is_rotation('falcon', 'flacon'))

The modulo operation handles negative amounts and amounts larger than the length. A string b is a rotation of a if it has the same length and occurs in a + a.

$ python rotate.py
  1 alconf
  2 lconfa
 -1 nfalco
  6 falcon
  8 lconfa
True
False

Truncating text

Since slices clip their bounds, a slice is a safe way to shorten text to a maximum width.

truncate.py
def truncate(text, width, ellipsis='...'):
    if len(text) <= width:
        return text
    return text[:width - len(ellipsis)] + ellipsis


titles = [
    'Python strings',
    'An old silent pond, a frog jumps into the pond',
    'Exactly twenty chars',
]

for title in titles:
    short = truncate(title, 20)
    print(f'{short:20}| {len(short)}')

Short texts are returned unchanged. Longer ones are cut so that the result, including the ellipsis, has exactly width characters. For cutting at word boundaries, textwrap.shorten is a better choice.

$ python truncate.py
Python strings      | 14
An old silent pon...| 20
Exactly twenty chars| 20

Slice objects

The slice syntax creates a slice object behind the scenes. We can create such objects ourselves and give them names.

slice_objects.py
date = '2026-11-19T14:05:33'

YEAR = slice(0, 4)
MONTH = slice(5, 7)
DAY = slice(8, 10)
TIME = slice(11, None)

print(date[YEAR], date[MONTH], date[DAY], date[TIME])
print(TIME)
print(TIME.start, TIME.stop, TIME.step)
print(DAY.indices(len(date)))

date[YEAR] is the same as date[0:4]. Missing values are stored as None. The indices method returns the bounds and the step adjusted to a sequence of the given length.

$ python slice_objects.py
2026 11 19 14:05:33
slice(11, None, None)
11 None None
(8, 10, 1)

Fixed-width records

Older systems and banks often exchange data in fixed-width files, where each field occupies a fixed range of columns.

accounts.txt
1001Alice Smith         0000125050EUR
1002Bob Brown           0000003999USD
1003Carol White         0001500000EUR

Named slices describe the layout in one place.

fixed_width.py
from pathlib import Path

FIELDS = {
    'id': slice(0, 4),
    'name': slice(4, 24),
    'balance': slice(24, 34),
    'currency': slice(34, 37),
}


def parse(line):
    rec = {key: line[field].strip() for key, field in FIELDS.items()}
    rec['id'] = int(rec['id'])
    rec['balance'] = int(rec['balance']) / 100
    return rec


text = Path('accounts.txt').read_text(encoding='utf-8')

for line in text.splitlines():
    rec = parse(line)
    print(f"{rec['id']} {rec['name']:12} {rec['balance']:>12,.2f} {rec['currency']}")

The FIELDS dictionary maps field names to column ranges. The dictionary comprehension slices each field out of the line and strips the padding. The balance is stored in cents without a decimal point, so we divide it by 100.

$ python fixed_width.py
1001 Alice Smith      1,250.50 EUR
1002 Bob Brown           39.99 USD
1003 Carol White     15,000.00 EUR

Slicing and Unicode

Indexes count code points, not the characters a reader sees. Some characters consist of several code points, and slicing can split them.

unicode_slice.py
import unicodedata

word = 'noe\u0308l'
flag = '\U0001F1F8\U0001F1F0'

print(word, len(word))
print(word[::-1])
print(word[:3])

nfc = unicodedata.normalize('NFC', word)
print(nfc, len(nfc), nfc[::-1])

print(flag, len(flag))
print([unicodedata.name(c) for c in flag])

The word is written with a plain e followed by a combining diaeresis, U+0308. It looks like four letters, but has five code points. Reversing puts the diaeresis before the e, so it lands on the l, and the slice [:3] cuts it off. Normalizing to the NFC form combines the two code points into one ë. Not every character has a precomposed form: a flag is always a pair of regional indicator symbols, and reversing it gives another pair, which is a different flag or no flag at all. The unicodedata module and third-party grapheme libraries help with such text.

$ python unicode_slice.py
noël 5
l̈eon
noe
noël 4 lëon
🇸🇰 2
['REGIONAL INDICATOR SYMBOL LETTER S', 'REGIONAL INDICATOR SYMBOL LETTER K']

Source

Common sequence operations – Python documentation

slice – Python documentation

In this article we have indexed and sliced strings in Python. See also Python list slice, Python slice function, Python find substring, and Python reverse.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.