7.4. String slices¶
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
The operator returns the part of the string from the “n-th” character to the “m-th” character, including the first but excluding the last.
If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string:
If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks:
An empty string contains no characters and has length 0, but other than that, it is the same as any other string.
- 4
- Incorrect! Slicing includes the first index but excludes the last. Try again.
- 5
- Correct! s[3:8] is "egran", which is five characters long, so "HELLO" is printed five times.
- 6
- Incorrect! Slicing includes the first index but excludes the last. Try again.
- Error, the for statement cannot use string slices.
- Incorrect! Slicing returns a sequence that can be iterated over with a for loop. Try again.
11-9-5: How many times is the word HELLO printed by the following statements?
s = "pomegranate"
for ch in s[3:8]:
print("HELLO")
- Python is cool
- Incorrect! The string slicing on line 2 takes out part of the original str. Try again.
- Pyt
- Incorrect! Indices in Python start at 0. Try again.
- yth
- Correct! str[1:4] starts with the character at index 1 and ends after the character at index 3.
- ytho
- Incorrect! The slice operator includes the first index and excludes the last. Try again.
11-9-6: What will be printed when the following executes?
str = "Python is cool"
str = str[1:4]
print(str)
- python
- Incorrect! That would be s[0:6]. Try again.
- rocks
- Incorrect! That would be s[7:]. Try again.
- hon r
- Correct! The space is considered a character.
- Error, you cannot have two numbers inside the [].
- Incorrect! String slicing requires a starting index and an ending index. Try again.
11-9-7: What is printed by the following statements?
s = "python rocks"
print(s[3:8])