Lecture

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 uses square brackets ([]) with an index number. In Python, indices start at 0.

Example of Using Indexing
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.

Example of Indexing Spaces
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.

Example of Negative Indexing
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
Mission
0 / 1

What is the value of word[2] in the following code?

word = 'Programming' letter = word[2]

P

r

o

g

Lecture

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result