Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Slicing with Index Function | String Manipulation and Operations
Data Types in Python

book
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:

python
word[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.

  1. Extract the word painful.
  2. Extract the word mistakes.
  3. Extract the word learn.

If you use all the methods that were explored, this task won't be challenging for you.

Solution

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?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 11
single

single

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

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt