Trimming Spaces
When people type, extra spaces slip in easily: one before a name, two after it. You can't see them, but Python can, and for Python, " Anna " isn't the same text as "Anna":
typed = " Anna "
print(typed == "Anna")
print(len(typed))This prints:
False
6The spaces count as characters, so the text has 6 of them. The method strip() returns the text without the spaces at its start and end; the spaces inside it stay. To see where a text starts and ends, print it between two other characters, for example square brackets in an f-string:
typed = " Anna Smith "
print(f"[{typed}]")
print(f"[{typed.strip()}]")This prints:
[ Anna Smith ]
[Anna Smith]Like the methods in the previous exercise, strip() doesn't change typed: it returns a new text. Besides spaces, it also removes tabs and line breaks from the ends.
Because strip() returns a text, you can call another method on the result straight away, in the same line. This is called chaining methods:
typed = " YES "
clean = typed.strip().lower()
print(f"[{clean}]")
if clean == "yes":
print("Great, let's go!")This prints:
[yes]
Great, let's go!Python goes from left to right: typed.strip() returns "YES", then lower() is called on that and returns "yes". You can chain as many methods as you need, as long as each of them returns a text.
Don't forget the parentheses. Without them, typed.strip doesn't call the method: it's the method itself, not a text. So typed.strip.lower() ends with AttributeError: 'builtin_function_or_method' object has no attribute 'lower'. Only texts have lower(), and a method isn't a text.
Instructions
- 1
Someone is signing up with the address in
email, typed with spaces around it and some capital letters. Create a variableclean_emailwith the address without those spaces and in lowercase, using a chain of two methods. Print it in square brackets, as in the example:[anna.smith@example.com]. Keep the lineemail = ...: the exercise also tries other addresses in it. - 2
Below, check whether the address is already registered: if
clean_emailis in the listregistered, printThis email is already registered., otherwise printWelcome!