How To: Advanced String Handling


Indexing

Slicing text

Here's a few lines of code that might seem strange at first:

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

What does it do? Let's run it in the console to see:

The code pulls apart the string "hello" character by character. When the number in the square brackets ([]) increases, we grab the subsequent character from the string.

Letters versus characters

Notice we talked about a string's characters, rather than its letters above. "Character" is just a more general way to refer to the individual pieces of a string; whereas "a letter" usually refers to things in the alphabet (A-Z), a character can be a letter, a number, a symbol, a punctuation mark .. anything!

String positions

The numbers in the square brackets ([]) in the code above refer to the string's indices. Each string is made up of characters, and each character has a position.

For example, the string "My phone" has these characters and positions:

Screenshot 2015-01-11 10.35.12.png

Spaces and punctuation have positions too, not just letters.

In general, to find a character's position, start at 0 and count upwards until you reach the character.

Why start counting at 0?

Computer scientists tend to count from 0, rather than 1. This has to do with the way computers store information, and it used to be a handy tool for software engineers, but it's become less important as computers have become more powerful and reliable. Now, we're still counting from 0 because that's what engineers in the past did, and many systems are programmed around how things used to be.

Syntax

When we put a number inside brackets next to a string, like "hello"[2], we're asking Python to "find and return the character in position 2 of the 'hello' string."

If you try to look up a position that doesn't exist in the string – say, position 99 of "hello" – you'll get an IndexError. That's Python's way of saying "I went to the 99th index of "hello" but didn't find anything – help!"

If you forget to put a number inside the square brackets, Python will also become confused and return a ParseError, which means "I couldn't understand, or parse through, what you wanted me to do."

Challenge

Write code that pulls the first letter from your name.

For example, if my name were "Trinket", I'd want to write code that returns a T from "Trinket", and if my name were "Ada", I'd want to return an A from "Ada".