The Slice Operator

A substring of a string is called a slice. Selecting a slice is similar to selecting a character:

The slice operator [n:m] returns the part of the string from the n’th character to the m’th character, including the first but excluding the last. In other words, start with the character at index n and go up to but do not include the character at index m.

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.

What do you think fruit[:] means?

Check your understanding

    rec-5-1: What is printed by the following statements?

    s = "python rocks"
    print(s[3:8])
    
  • python
  • That would be s[0:6].
  • rocks
  • That would be s[7:].
  • hon r
  • Yes, start with the character at index 3 and go up to but not include the character at index 8.
  • Error, you cannot have two numbers inside the [ ].
  • This is called slicing, not indexing. It requires a start and an end.

    rec-5-2: What is printed by the following statements?

    s = "python rocks"
    print(s[7:11]*3)
    
  • rockrockrock
  • Yes, rock starts at 7 and goes thru 10. Repeat it 3 times.
  • rock rock rock
  • Repetition does not add a space.
  • rocksrocksrocks
  • Slicing will not include the character at index 11. Just up to it (10 in this case).
  • Error, you cannot use repetition with slicing.
  • The slice will happen first, then the repetition. So it is ok.

Note

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

Next Section - Strings are Immutable