~ Advanced String Handling


Slicing text

In the last lesson, we talked about how we can pull single characters from strings. Here, we're going to explore how we can pull several characters at once.

Slicing from the beginning

Here's some more code. Can you guess what it does?

    "hello"[0:]
    "hello"[1:]
    "hello"[2:]
    "hello"[3:]
    "hello"[4:]
    "hello"[5:]

Let's run it to see:

"hello"[1:] goes from the e in position 1 to the end – the colon (:). So it looks like the [number:] command slices a string from the numbered position until the string's end.

Slicing from the end

What about this code?

    "hello"[:0]
    "hello"[:1]
    "hello"[:2]
    "hello"[:3]
    "hello"[:4]
    "hello"[:5]

Let's try it:

"hello"[:1] goes from the string's start to "just before" position 1, which returns an h, and "hello"[:0] goes from the string's start to "just before" position 0, which returns an empty string.

The [:number] command, after a string, slices the string from its front – position 0 – until just before the numbered position.

Slicing from the middle

What if we wanted to get characters from the middle of the string? Say, return the "ll" from "hello"?

One way to think about this is saying we want to slice from the beginning and the end, so we'll have to put position numbers on both sides of the colon, like this:

    "hello"[0:1]
    "hello"[1:2]
    "hello"[0:3]
    "hello"[3:4]
    "hello"[2:4]
    "hello"[4:5]

which, when run, looks like this:

"hello"[2:4] is the code that gives us back ll.

In English, that code says "hey Python! Please look at the string 'hello' and give me back the characters between position 2 and just before position 4."

Challenge

Write a line of code that turns the string "san francisco" into "San Francisco" There's a few pieces you'll need:

  • The string "san francisco" (which you might need to use more than once.) These are the only letters you can type – no "S" or "F" allowed.
  • Ways of changing strings. Turning lowercase letters to capital ones might be especially helpful ...
  • The string slicing we just covered

Good luck!