Indexing & Slicing

Access single characters or ranges of a string by position.

Syntaxtext[index] text[start:end]

Each character in a string has a position called an index, starting at 0. Negative indexes count from the end, so -1 is the last character.

Slicing

A slice text[start:end] returns a substring. The character at end is not included. Leave a side blank to go to the beginning or end.

String indexing and slicing of the word PYTHONPYTHON012345-6-5-4-3-2-1word[0:3] = "PYT"
Each character has a positive index from the start and a negative index from the end.

Example

Example · python
word = 'PYTHON'
print(word[0])
print(word[-1])
print(word[0:3])
print(word[3:])

# Output:
# P
# N
# PYT
# HON

When to use it

  • A parser extracts the file extension from a filename string using negative indexing.
  • A validation function checks the first character of a username to ensure it is a letter.
  • A data cleaner slices the first 10 characters of a description to create a short preview.

More examples

Access characters by index

Accesses specific characters using positive (from start) and negative (from end) indices.

Example · python
text = 'Python'
print(text[0])    # P
print(text[-1])   # n
print(text[2])    # t

Slice a substring

Slices the start and end of a URL string using [start:end] notation.

Example · python
url = 'https://example.com/page'
protocol = url[:5]      # 'https'
path = url[19:]         # '/page'
print(protocol, path)

# Output:
# https /page

Slice with step

Uses the step parameter in slicing to skip characters or reverse the entire string.

Example · python
s = 'abcdefgh'
print(s[::2])    # aceg  (every other character)
print(s[::-1])   # hgfedcba  (reversed)

Discussion

  • Be the first to comment on this lesson.