Course contentsLesson 4 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 04

Strings and input

Edit lesson

Work with text, format messages, and receive input from a user.

15 minProgress saves on this device
In this lesson
  • 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.

Format a messagepython
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.

Clean textpython
raw = "  Python  "
clean = raw.strip().lower()
print(clean)       # python
print(len(clean))  # 6

Read 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.

Ask for a numberpython
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.

Knowledge check

What type does input() return?

Try first; feedback appears after you check.
Apply it

Your turn

Ask for a favorite topic and print it without surrounding whitespace.

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson