← Deeper Python in the console

Working with text

Tidy typed text with strip() and lower(), cut it into words with split(), and pick out a word by its place.

Every search box, chat window and voice assistant starts the same way: tidy what was typed, then cut it into words.

What people type is messy: extra spaces, capitals, more words than you expect. Text has its own commands, called with a dot (command.lower()), that tidy it and cut it up. In this course you build the parts of a text adventure, starting with understanding a typed command.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

text.py
command = "  Go NORTH "
command = command.strip().lower()
print(command)
print(len(command))

strip() removes spaces from both ends of the text; lower() turns capitals into small letters. Each gives back new text. What will len(command) be?

What is the second line it prints?

RunRun it and compare the result with your prediction.

Run

Run it and type a command such as go north, then try TAKE lamp and look. split() cuts the text into a list of words at the spaces, so words[0] is the first word.

text.py
command = input("What do you do? ")
command = command.strip().lower()
words = command.split()
print("You typed " + str(len(words)) + " words.")
if len(words) == 2:
    print("Verb: " + words[0])
    print("Thing: " + words[1])
else:
    print("Try two words, such as: go north")
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

text.py
command = input("What do you do? ")
command = command.strip().lower()
words = command.split()
print("You typed " + str(len(words)) + " words.")
if len(words) == 2:
    print("Verb: " + words[0])
    print("Thing: " + words[1])
else:
    print("Try two words, such as: go north")

Follow one command through the tidying.

How split() cuts a longer command.

A door that will not open.

You type Take LAMP (with spaces around it). What is words[1]?

You type: pick up the red key. How many words does split() give?

You type Yes and the door stays shut. Click the line that causes it.

ModifyChange the code on purpose and check the result.

Modify

Make the program say goodbye when the command is quit.

Need a hint?

Before the other checks, add if command == "quit": and print a goodbye. Change the next if to elif.

Accept only the verbs go, take and look. For any other verb, print I don't understand and the word.

Need a hint?

in checks whether something is in a list: words[0] in ["go", "take", "look"].

Another hint

Print the verb and thing only for known verbs; otherwise print I don't understand.

Try it yourselfYour edits are saved in this browser.

Say goodbye when the command is quit.

    Run your program. This ticks when your code does all of the above.

    Only accept the verbs go, take and look.

      Run your program. This ticks when your code does all of the above.

      MakeBuild something new using what you have learned. Expect a few tries; that is normal.

      Make initials

      Ask for someone's full name. Print their initials (the first letter of each word, in capitals) and their whole name in capitals. word[0] is the first letter of a word, just as words[0] is the first word. Test it with extra spaces and with three names.

      Try it yourselfYour edits are saved in this browser.

      Ask for a full name, then print the initials and the name in capitals.

        Run your program. This ticks when your code does all of the above.

        Info

        Where this leads

        Next lesson keeps things in a list that grows and shrinks: the adventurer's bag.

        A website's search finds "Python" when you type " python ". What has it done first?

        For teachers

        Students tidy typed text with strip() and lower(), cut it into words with split(), pick words by place, and see why text must be tidied before it is compared. It is the first part of a text adventure. About 45 minutes.

        Open the teacher guide: answers, solutions, slides and a worksheet.

        Students will be able to

        Before class

        Read the unit primer first. Text has its own commands, called with a dot: command.strip() removes spaces at both ends, .lower() and .upper() change capitals, and .split() gives a list of words. Each gives back new text; the original is unchanged unless you store the result (command = command.strip()). They can be chained: input("> ").strip().lower(). The bug task is the reason they matter: "Yes" == "yes" is False. in checks whether something is in a list.

        Running the lesson

        1. Predict: write " Go NORTH " on the board and cross off what strip() and lower() change, then count.
        2. Run: ask students to try to break it: extra spaces, capitals, one word, five words.
        3. Investigate: words[1] is the second word, as list places start at 0.
        4. Bug task: ask how many ways a person could type yes (Yes, YES, yes with a space).
        5. Make: word[0] is the first letter of a word, the same idea as words[0].

        The hard part (on purpose)

        Seeing why Yes and yes differ, and what split() gives back. Have them print the tidied text and the list of words before they fix the comparison.

        When students get stuck

        Stretch and support

        Stretch: Accept short commands too, such as n for go north, by checking a list of short forms.

        Support: Give students the line that splits the name, and ask them to build the initials with a loop.

        Where it leads

        Next lesson keeps an inventory in a list (append, remove, in). The parser from this lesson comes back in the text adventure.

        What each step is for

        Now you can
        Next lesson2. A bag that growsAdd to a list with append(), take out with remove(), check with in, and list it with join().