Python String Indexing and Slicing: Essential Techniques for Composite Data Types
This tutorial explains Python's string indexing and slicing, covering zero‑based indices, the start:end:step syntax, negative indices, step rules, and multiple concrete examples that demonstrate how to extract and manipulate substrings.
In Python, an index (also called a subscript) identifies the position of an element in a sequence, starting from 0; using an index you can retrieve the character at that position.
str1 = "welcome"
# print(str1[3]) # cSlicing creates a new string by copying a specified range from the original string.
The slicing syntax is string[start:end:step] where:
start – the starting index (included in the result).
end – the ending index (excluded from the result).
step – the stride; the default value is 1.
Example string: str2 = "welcome to beijing" Typical slice operations and their outputs:
print(str2[0:3]) # wel (includes start, excludes end)
print(str2[1:]) # elcome to beijing (from start index to end)
print(str2[:4]) # welc (from beginning up to index 4)
print(str2[1:4:2]) # ec (step of 2)
# print(str2[1:4:0]) # step cannot be zero – would raise an error
print(str2[::]) # welcome to beijing (full copy)
print(str2[::-1]) # gnijieb ot emoclew (reversed string)
print(str2[-9:-3]) # o beij (both indices negative, counting from the right)The corresponding output lines are:
wel
welcome to beijing
welc
ec
welcome to beijing
gnijieb ot emoclew
o beijLisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
