Python & data · Lesson 04
Strings and input
Work with text, format messages, and receive input from a user.
- Format and inspect text
- Use common string methods
- Convert and validate user input
Helpful background: Understand variables and basic types.
Create and combine text
A string is a sequence of characters. Use single or double quotes consistently, and choose the other kind when it makes a quoted character easier to read.
An f-string inserts the value of an expression inside braces. This makes messages easier to read than converting every value by hand.
name = "Mira"
books = 3
print(f"{name} borrowed {books} books.")Inspect and transform strings
len() counts the characters in a string, including spaces. String methods such as strip() and lower() return new strings; they do not change the original string.
Indexing starts at zero. Before accessing an index, make sure the string is long enough.
raw = " Python "
clean = raw.strip().lower()
print(clean) # python
print(len(clean)) # 6Read a response
input() displays a prompt and reads a line of text. Its result is always a string, even when a person types digits. Convert numeric text before doing arithmetic.
This example waits for input when run in a terminal. int() raises ValueError if the entered text is not a valid integer, so real programs should handle invalid input.
answer = input("How many books? ")
count = int(answer)
print(f"Next time, try {count + 1}.")Be careful with assumptions
An empty response is still a string. Use strip() when leading and trailing spaces do not matter, and decide what your program should do when the response is empty.
Checking input and handling errors are covered again in the files and exceptions lesson.
What type does input() return?
Your turn
Ask for a favorite topic and print it without surrounding whitespace.
topic = input("Favorite topic? ").strip() print(f"You chose {topic}.")
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited