59.0k views
0 votes
Imagine you have a 10-character string stored in the variable myString. You want to pull out the first five characters. Which of the following lines of code would successfully generate a slice of the 10-character string holding only the first five characters?

a. myString[5]
b. myString[:-5]
c. myString[0:6]
d. myString-15:-5]
e. myString[0:10:2]

1 Answer

1 vote

Answer:

b. myString[:-5]

d. myString[-15:-5]

Step-by-step explanation:

I believe you have a typo in d. It must be d. myString[-15:-5]

Slicing can be done:

myString[starting_index, stopping_index, step] (step is optional). If you do not specify the starting index, it will start from the 0 as in b. If you write a range that is not in the range, as in d, Python will replace it with either 0 or length of the string (In this case, it is replaced with 0 because the starting index must be smaller than stopping index)

a. myString[5] → This will give you the sixth character

b. myString[:-5] → This will give you the first five characters

c. myString[0:6] → This will give you the first six characters

d. myString-15:-5] → This will give you the first five characters

e. myString[0:10:2] → This will give you the first, third, fifth, seventh, and ninth characters

User Bratao
by
5.7k points