Indexing and Slicing
To effectively work with text data, you often need to extract specific characters or portions of a string. Python's indexing and slicing provide powerful, concise ways to do exactly that, letting you precisely target the data you need.
Accessing Single Characters
Every character in a string occupies a specific position, identified by an index. Python uses zero-based positive indexing, starting from 0 for the first character. It also supports negative indexing, which counts from the end of the string, with -1 representing the last character. This dual approach offers flexibility when you need to retrieve characters from either end of a string.
Extracting Substrings with Slicing [start:stop]
While indexing retrieves a single character, slicing allows you to extract a contiguous sequence of characters, known as a substring. The basic syntax is [start:stop], where start is inclusive and stop is exclusive. This means the character at the start index is included, but the character at the stop index is not.
You can omit the start or stop index for convenience. Omitting start defaults to 0, and omitting stop defaults to the end of the string. Using [:] creates a full copy of the string, which can be useful when you need to work with a mutable version of the string (e.g., converting to a list of characters) without affecting the original.
my_string[2:2] return?Advanced Slicing with a Step [start:stop:step]
Beyond start and stop, slicing also accepts an optional step parameter. This allows you to skip characters, taking every Nth character within the specified range. The step value determines the increment between characters in the resulting substring, providing a powerful way to extract non-contiguous sequences.
A common trick to reverse a string is my_string[::-1]. This uses a negative step to iterate backward through the entire string, effectively creating a reversed copy.
'abcdefg'[1::2]?Indexing and slicing only retrieve characters or substrings; they do not modify the original string. Any operation that appears to change a string, such as my_string = my_string[2:], actually creates a new string and reassigns the variable, leaving the original string object untouched in memory.
Positive indices start at
0from the left; negative indices start at-1from the right.Use
string[index]to access a single character at a specific position.Slicing
string[start:stop]extracts a substring;startis inclusive,stopis exclusive.Omitting
startdefaults to0, and omittingstopdefaults to the string's end.The optional
stepparameter instring[start:stop:step]determines the increment between characters.A negative
step(e.g.,[::-1]) is a concise way to reverse a string.Indexing and slicing always return new strings or characters, never modifying the original string due to Python's string immutability.