Python input(): Strip, Lowercase and Split User Input
Python's input() returns exactly what the user typed, so cleaning input means trimming, lowering and splitting that text before you use it.
Read Reading Input first. This lesson also uses String Methods and Lists.
Ask on a separate line
input() with no prompt reads an answer without showing a question. Print the
question first if you want the answer typed underneath it.
print("What is your favourite colour?")
colour = input()
print("You chose", colour)
Run it, type blue, and press Enter. The output depends on what you type; with
blue the console shows:
What is your favourite colour?
blue
You chose blue
Choose this layout for long questions or menus. Use a prompt inside input()
for short questions, so question and answer share a line.
Trim spaces and ignore case
Users add stray spaces and capitals. "Yes " and "yes" are different
strings, so a plain comparison fails.
answer = " Yes " # what the user typed
print(answer == "yes")
clean = answer.strip().lower()
print(clean == "yes")
This prints False, then True. strip() removes spaces at both ends.
lower() makes every letter lowercase. Neither changes answer itself; each
returns a new string.
Split one answer into several values
split() breaks text at spaces and returns a list of strings.
line = "Ada 12 Melbourne" # what the user typed
parts = line.split()
print(parts)
print(parts[1])
This prints ['Ada', '12', 'Melbourne'], then 12. Each part is still text,
so convert parts[1] with int() before doing maths. Pass a separator to
split on something else, such as line.split(",").
The choice that most often confuses: split() with no argument treats any run
of spaces as one gap, but split(" ") splits at every single space.
line = "Ada 12" # two spaces
print(line.split())
print(line.split(" "))
The second list holds an empty string '' between the two spaces. Use plain
split() for typed answers.
Note: if the user types fewer words than you expect, parts[2] raises
IndexError. Check len(parts) first. The examples here use fixed strings in
place of input() so they give the same output every run; a real program reads
the line with input() and still needs to handle empty or unexpected answers.
See also: String Methods, Data Validation.
Your turn
line is what a user typed. Clean it, split it into a name and a score, and
print the name in lowercase and the score doubled.
line = " SAM 21 " # what the user typed
# add your code: strip and split line, then print the lowercase name and int(score) * 2
Expected output
sam
42