Indexing & Slicing
Access single characters or ranges of a string by position.
Syntax
text[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.
Example
word = 'PYTHON'
print(word[0])
print(word[-1])
print(word[0:3])
print(word[3:])
# Output:
# P
# N
# PYT
# HONWhen 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.
text = 'Python'
print(text[0]) # P
print(text[-1]) # n
print(text[2]) # tSlice a substring
Slices the start and end of a URL string using [start:end] notation.
url = 'https://example.com/page'
protocol = url[:5] # 'https'
path = url[19:] # '/page'
print(protocol, path)
# Output:
# https /pageSlice with step
Uses the step parameter in slicing to skip characters or reverse the entire string.
s = 'abcdefgh'
print(s[::2]) # aceg (every other character)
print(s[::-1]) # hgfedcba (reversed)
Discussion