Selecting Specific Parts of a String Using Indexing
Indexing
is a process to specify the position or order to access a specific element within a data structure.
To select or access a specific part of a string, use the indexing operator, [number]
. Indexing allows you to extract specific characters from a string.
How to Use
String indexing involves using square brackets ([]
) with an index number. In Python, indexes start at 0.
word = "Programming" first_letter = word[0] # 1st character 'P' third_letter = word[2] # 3rd character 'o'
Spaces are also recognized as part of the string, and you can access spaces through indexing.
word = "Programming Language" word[11] # 12th character ' ' (space)
Negative Indexing
In Python, you can use negative indexes to access elements from the end of a string. The -1
index 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 for specific characters or to set conditions based on specific characters 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
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result