Picking Out Characters in a String
Imagine you are on a game show with three luxury cars lined up. If you want to choose the second car, you'd say "I want the second car." Similarly, in programming, you use numbers to pick specific elements in a string or sequence.
In Python, you can select a particular element from a sequence by typing an integer inside square brackets [ ]. This is called indexing. To select a range of elements, you use slicing, which involves specifying a starting and ending index separated by a colon :.
Indexing and Slicing Examples
- Indexing: Picking a Single Character
You can select a single character from a string by its position. Positions start at 0, not 1.
|
Combining Characters: Using Multiple Indexes
You can combine characters from different positions to create new strings.
|
Slicing: Picking a Substring
To pick a range of characters, specify a starting index and an ending index. The ending index is not included in the result.
|
To summarize:
- Indexing: Use square brackets [ ] with a number to pick a specific character from a string. For example, mystring[0] gives the first character.
- Slicing: Use a colon : between two numbers inside square brackets to pick a range of characters. For example, mystring[1:3] gives the characters from index 1 to index 2.
- Combining Characters: You can combine different characters to form new strings.
- Splitting: You can split a string into a list of parts based on a specific character or substring.