Challenge: Slicing with Index Function
Task
Swipe to start coding
Try to extract words using slicing, but in a little bit more complicated way. The syntax of slicing is the following:
pythonword[start_index:end_index]
To find the start_index
, use the index()
method, and to find the end_index
, use the index()
method, and add the length of the word.
- Extract the word
painful
. - Extract the word
mistakes
. - Extract the word
learn
.
If you use all the methods that were explored, this task won't be challenging for you.
Solution
99
1
2
3
4
5
6
7
8
9
10
11
string = "It can be painful to learn from mistakes"
# Extract necessary words
learn = string[string.index('learn'):string.index('learn') + len('learn')]
painful = string[string.index("painful"):string.index("painful") + len("painful")]
mistakes = string[string.index("mistakes"):string.index("mistakes") + len("mistakes")]
print("The variable learn equals:", learn)
print("The variable painful equals:", painful)
print("The variable mistakes equals:", mistakes)
Everything was clear?
Thanks for your feedback!
Section 3. Chapter 11
single
99
1
2
3
4
5
6
7
8
9
10
11
string = "It can be painful to learn from mistakes"
# Extract necessary words
learn = string[string.index('learn'):string.index('learn') + ___]
painful = string[string.___(___):___ + ___]
mistakes = string[___]
print("The variable learn equals:", learn)
print("The variable painful equals:", painful)
print("The variable mistakes equals:", mistakes)
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat