Selecting Specific Parts of a String Using Indexing
Indexing
refers to specifying the position of an element in a data structure.
To access a specific character in a string, use square brackets [number]
with the character’s index number. Indexing allows you to extract specific characters from a string.
How to Use
String indexing uses square brackets ([])
with an index number.
In Python, indices start at 0, meaning the first character is at position 0. This is important to understand, as incorrect indexing can lead to errors or unexpected results.
word = "Programming" first_letter = word[0] # 1st character 'P' third_letter = word[2] # 3rd character 'o'
Spaces are also recognized as part of a string and can be accessed through indexing.
word = "Programming Language" word[11] # 12th character ' ' (space)
Negative Indexing
In Python, you can use negative indices to access elements from the end of a string.
The index -1
represents the last character of the string.
word = "Programming" last_letter = word[-1] # Last character 'g' second_last = word[-2] # Second to last character 'n'
Applications of Indexing
String indexing is used when you need to utilize the value of a specific part of a string.
For example, it can be used to check specific characters or set conditions based on them within a string.
# Example of Checking a Specific Character word = "Programming" if word[0] == 'P': # Check if the first character of the string in the word variable is 'P' print("The string starts with 'P'.") # Execute if the condition is true
What is the value of word[2] in the following code?
word = 'Programming' letter = word[2]
P
r
o
g
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result