Fill in

Side Quest: Slice the Edges

Slices are forgiving. They never crash, even at the very edges of a string. Let's poke at the edges of word = "MOON":

word = "MOON"
print(word[1:2])    # O     one character, still a slice
print(word[2:2])    #       start == stop: empty ""
print(word[3:1])    #       start after stop: also ""
print(word[2:99])   # ON    stops at the real end
print(word[10:])    #       starts past the end: ""
print(word[-10:])   # MOON  too far left starts at 0

Index or slice?

A plain index must point at a real character. word[10] crashes with an IndexError. A slice hands back whatever characters are really there, even none at all. The result is always a string, sometimes the empty string "".

That matters with real text, because it comes in every length. A visitor might type a short name, or no name at all. name[0] crashes on an empty name, but name[:1] safely gives "".

Pip tip: When you test text code, always try three lengths: a long one, a tiny one and the empty string "".

Assignment

The Guild's signboard shows short previews of visitors' names. Replace each ___ with a slice (it needs a colon :) so the code works for any name, even "":

  1. preview: the first 5 characters (the whole name if it's shorter).
  2. initial: the first character. Use a slice, so an empty name gives "" instead of crashing.
  3. rest: everything after the first character.
  4. ending: the last 3 characters (the whole name if it's shorter).