Python String Indexing
Category Programming Techniques
Strings are ordered collections of characters, and individual elements can be accessed by their position. In Python, characters in a string are accessed via indexing, which starts at 0.
Python also supports negative indexing, which means accessing elements from the end of the string, where the last character is -1, the second to last is -2, and so on.
Below is a summary of Python indexing and slicing:
1. Indexing to Access Specific Offset Elements
The first element in the string has an offset of 0
The last element in the string has an offset of -1
str[0]
retrieves the first elementstr[-2]
retrieves the second to last element
2. Slicing to Extract Portions of the String
The upper boundary is generally not included in the extracted string
If no values are specified, the default boundaries for slicing are 0 and the length of the sequence
str[1:3]
retrieves characters from offset 1 up to, but not including, offset 3: "tr"str[1:]
retrieves characters from offset 1 to the last character (including the last character): "tring"str[:3]
retrieves characters from offset 0 up to, but not including, offset 3: "str"str[:-1]
retrieves characters from offset 0 up to, but not including, the last character: "strin"str[:]
retrieves all elements from the start to the end of the string: "string"str[-3:-1]
retrieves characters from offset -3 up to, but not including, offset -1: "in"str[-1:-3]
andstr[2:0]
retrieve an empty string, with no system error: ""Slicing can also include a step,
str[::2]
outputs: "srn"
** Click to Share Notes
-
-
-