I would introduce this with a problem/relatable example, such as:
I'd make a little text-based program that printed out:
Welcome to Birdr, your favorite social media site for bird-watching.
Would you like to make an account?
What is your first name?
> [I'd ask the students for a fake first name]
What is your last name?
> [I'd ask the students for a fake last name]
Welcome, [First Last]
When typing in the students' suggestions for names, I'd pretend to be having difficulty typing. I'd make a big show of hunting for letters, struggling with capitalization, etc. and I'd make sure to leave several spaces at the beginning and end of words.
Then, once the program had run, I'd ask the class the following questions:
- How is this working? What have we learned about so far that's being used here? (Printing, input, variables, strings). I'd show them the source code at this point, which would have been hidden until now.
- Look at this weird formatting (e.g.,
Welcome, Harry Potter ), why is that happening? (I typed extra spaces around both words)
Often, when we're getting user input, people will make mistakes like adding extra spaces before or after words. Luckily, there's a way to clean that up! We can use Python's
strip() gets rid of extra "whitespace" before and after a string. Whitespace is stuff like spaces.
I'd show adding it in and then running the program again. Then we'd talk about the difference between using it on each of the inputted variables vs using it on the concatenated string and we'd see an example of each. I'd ask the students to point out the difference and ask them to hypothesize why they were different.
Finally, I'd ask the class to brainstorm other situations that
strip() might be useful.