Strings are text, and almost every program works with text somewhere. This lesson covers how to read text from a user, take it apart, and put it back together.
Reading input
input() pauses the program, waits for the user to type a line and press Enter, then gives you what they typed:
name = input()
print("Hi,", name)You can pass a prompt to show first: input("What's your name? ").
input() always returns a string, even if the user types a number. To do math, convert it:
age = int(input())
price = float(input())
print(age + 1)
print(price * 2)Warning
"5" + "3" is "53", not 8. If you forget to convert, Python joins the text instead of adding the numbers. If the user types something that isn't a number, int() crashes with a ValueError.
In the puzzles, each line of the Input box is one call to input().
Concatenation and repetition
Use + to join strings and * to repeat them:
first = "Ada"
last = "Lovelace"
print(first + " " + last) # Ada Lovelace
print("ha" * 3) # hahaha+ only joins strings with other strings. "Age: " + 30 is an error until you write "Age: " + str(30). There's a cleaner way, which you'll see in a moment.
Indexing
Each character has a position called an index, and counting starts at 0:
p y t h o n
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
word = "python"
print(word[0]) # p
print(word[3]) # h
print(word[-1]) # n (negative numbers count from the end)
print(len(word)) # 6Asking for an index that doesn't exist raises an IndexError. Strings are immutable, so you can read word[0] but you can't do word[0] = "P". You make a new string instead.
Slicing
A slice grabs a piece of a string: text[start:stop:step]. It includes start but stops before stop.
word = "python"
print(word[1:4]) # yth
print(word[:2]) # py (start defaults to 0)
print(word[2:]) # thon (stop defaults to the end)
print(word[::2]) # pto (every second character)
print(word[::-1]) # nohtyp (a negative step goes backward)Tip
[::-1] is the classic way to reverse a string.
String methods
A method is a function that belongs to a value. You call it with a dot. Methods never change the original string. They return a new one.
| Method | What it does | Example | Result |
|---|---|---|---|
.upper() | all capitals | "hi".upper() | "HI" |
.lower() | all lowercase | "Hi".lower() | "hi" |
.title() | Capitalize Each Word | "ada lovelace".title() | "Ada Lovelace" |
.strip() | trim spaces from both ends | " hi ".strip() | "hi" |
.replace(a, b) | swap text | "cat".replace("c", "b") | "bat" |
.find(x) | index of first match, or -1 | "hello".find("l") | 2 |
.count(x) | how many times x appears | "banana".count("a") | 3 |
.startswith(x) | begins with x? | "python".startswith("py") | True |
Methods can be chained left to right:
messy = " aDA "
print(messy.strip().title()) # Adaf-strings
An f-string lets you put variables and expressions straight into text. Add an f before the opening quote and wrap anything dynamic in { }:
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print(f"Next year: {age + 1}")Output:
Ada is 36 years old.
Next year: 37
You can also control formatting after a colon. .2f means "a float with 2 decimals":
price = 4.5
print(f"Total: ${price * 3:.2f}") # Total: $13.50No conversion is needed, because f-strings turn numbers into text for you.
Why not just use + or commas?
You can, and sometimes that's fine. But f-strings are easier to read once a message has more than two pieces, they handle numbers without str(), and they give you formatting like :.2f for free.
Using input in calculations
Combine everything: read, convert, calculate, display.
width = int(input())
height = int(input())
area = width * height
print(f"A {width} by {height} rectangle has an area of {area}.")With the input 4 and 5, this prints A 4 by 5 rectangle has an area of 20.
Now try it yourself. The next step is three puzzles that read input and work with text.