PythonLesson 4 of 16
Strings and f-strings in Python
A string is any text in quotes. You can measure it, shout it in capitals and build it from pieces with an f-string.
Key points
- len(s) is the length; s.upper() and s.lower() change the case
- s.title() capitalises the first letter of each word
- f"...{x}..." drops a variable's value right into the text
- {price:.2f} prints a number with two decimals
- str(5) turns a number into text, int("12") turns text into a number
Example
name = "anna"city = "Lisbon"print(name.title())print(len(city), city.upper())print(f"Hi, {name.title()}! Welcome to {city}.")price = 4.5print(f"Price: {price:.2f}")Methods are called with a dot and return a new string, so name is still "anna". The :.2f format adds the trailing zero in 4.50.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Build a receipt line from item, price and qty. The output must be exactly: Latte x2 = 7.00
Output
What your program prints appears here.