String Indexing
Strings are ordered sequences. Every character has a unique position, called an index. Indexing starts at 0.
| Character | P | y | t | h | o | n |
|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
Accessing Characters
Use square brackets [] after the string variable to access a specific character.
python language = 'Python' first_char = language[0] third_char = language[2] print(first_char) # Output: P print(third_char) # Output: t
Negative Indexing
Negative indices count from the end of the string:
-1is the last character.-2is the second-to-last character.
python last_char = language[-1] print(last_char) # Output: n
String Slicing
Slicing allows you to extract a substring (a segment of the string). The syntax is [start:stop:step].
Note: The stop index is exclusive (the character at the stop index is not included).
python text = 'Programming'
Get characters from index 2 up to (but not including) 6
slice1 = text[2:6] # 'ogra'
Slice from the beginning to index 5
slice2 = text[:5] # 'Progr'
Slice from index 5 to the end
slice3 = text[5:] # 'amming'
Slice using step (every second character)
slice_step = text[0:11:2] # 'Pormi'
Reverse the string (step of -1)
reversed_text = text[::-1] # 'gnimmarborP'