Python Glossary Русский

all Python 3Strings (str)term

String slicing

indexing/slicing

Taking a substring by a range of indices. s[a:b] runs from a to b (b excluded), s[a:b:c] takes step c. s[::-1] reverses the string.

Syntax

s[a:b]  |  s[a:b:c]  |  s[::-1]

A slice never goes out of range: s[10:20] on a short string just yields an empty string, while s[10] raises IndexError — handy, but it also hides typos. Every slice allocates a fresh string of length b-a, so chopping a string piece by piece in a loop costs more than iterating over it directly. With a negative step the bounds read right to left: you want s[5:1:-1], not s[1:5:-1].

Examples

s = 'abcdefgh'
print(s[2:5])
# → 'cde'
print(s[:3])
# → 'abc'
print(s[5:])
# → 'fgh'
print(s[::-1])
# → 'hgfedcba'
print(s[::2])
# → 'aceg'
print(s[-3:])
# → 'fgh'
print(s[1:7:2])
# → 'bdf'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy