…
…
Python Programming Fundamentals · Lesson 22 / 40 · Strings
PreviewIn this lesson you will
\n or triple quotes, and explain that a number format changes only how a value looks, not the valueYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In lesson 4 you printed a single aligned line of Corner Café's receipt. Now Ada wants the whole receipt, with the title in the middle, the quantity, unit price, and amount one under another, and the total at the bottom. In the weekend sales report, big numbers should not look like a pile such as 1250000 but have thousands separators like 1,250,000, and the report should show how much of the target was reached as a percentage; in this lesson we will build both with functions that return the line.
At the end of the lesson, the receipt_line function you write and the small receipt program that uses it will produce this output:
Output==========CORNER CAFÉ==========
Latte 2 x 4.25 8.50
Brownie 3 x 3.75 11.25
-------------------------------
TOTAL 19.75Three things stand out on this receipt: the title is centered with equals signs, the numbers line up exactly one under another, and every line has the same width. To do this, you will learn three new skills:
Why do you need new formats? Because numbers are not read the same way everywhere. If a week of sales is written as 1250000, the eye has to count the digits one by one: is it one million, or one hundred twenty-five thousand? If a rate is written as 0.1834, the reader has to convert it in their head to "about 18 percent". If a receipt number is 7, it does not look as wide as the other receipts at the register; 007 would sit neatly in a list. An f-string solves all three with a small format specifier written after the colon.
You know the formats from lesson 4. In this lesson we add three new rows to the table and a rule for combining them:
| Format | Meaning | Example | Result |
|---|---|---|---|
:.2f (remember) | 2 places after the decimal point | f"{3.5:.2f}" | 3.50 |
:<10, :>8 (remember) | Push left or right in a fixed width | f"{85:>6}" | 85 |
:, | Separate thousands with a comma | f"{1250000:,}" | 1,250,000 |
:.1% | Multiply by 100, write 1 decimal place, add % | f"{0.1834:.1%}" | 18.3% |
When you combine formats, the order is fixed: first alignment and width, then the comma, and the decimal part last. You write :>12,.2f; a mixed order such as :.2f,>12 gives an error.
The percent format is the one people confuse most. :.1% does not just put a % sign at the end of the number; it first multiplies the number by 100, then writes it with one decimal place, and adds % last. That is why you keep the rate as a float like 0.1834, not as 18.34. Python writes these lines in the US layout: it separates thousands with a comma and decimals with a decimal point (1,234.50). Other layouts need an extra step; we will build one in section 4 with the replace method you learned in lesson 21. In the rest of this course we use the US layout.
Example 1: Numbers in the weekly report
revenue = 1250000 rate = 0.1834 receipt_no = 7 amount = 1234.5 print(f"Revenue: ${revenue:,}") print(f"Target reached: {rate:.1%}") print(f"Receipt no: {receipt_no:03}") print(f"Amount: ${amount:,.2f}") print(amount)
OutputRevenue: $1,250,000
Target reached: 18.3%
Receipt no: 007
Amount: $1,234.50
1234.5Look at the last line. One line earlier amount appeared on screen as 1,234.50, but print(amount) still writes 1234.5. The format specifier affected only the string that f-string produced; it did not touch the number in the amount box. A common mistake is to think the variable itself was "rounded" or "given commas" after you used :.2f or :,. The variable stays the same; you can keep calculating with it.
Now test one of the shortest specifiers. Think about what the two digits mean in zero padding, then choose.
What does this code print?
print(f"{7:03}")
Instead of memorizing the table, learn to recognize each code by matching it with its result. The last row in the block below shows something new: if you write a character before the width, the empty space is filled with that character instead of spaces. You will see this in detail in the next section. Some options are not used in the list; they are typical misconceptions.
Match each f-string with the string it produces.
For each row, pick its match from the list, then check.
f"{3.5:.2f}"f"{1250000:,}"f"{0.1834:.1%}"f"{7:03}"f"{0.5:.0%}"f"{1234.5:,.2f}"f"{'ab':*>5}"Numbers lining up on a receipt is no accident. For each column you set aside a fixed-width field, and the value leans to one side inside it. In lesson 4 you saw the < (left) and > (right) signs; the third is the ^ sign, which puts the value in the middle of the field. If the value is shorter than the field, the rest is filled. If the value is longer than the field, Python does not cut it: the field grows by itself and the whole value is written. This is a safety feature (no information is lost) but it breaks the column; that is why you choose the field width according to the longest value.
| Column | Aligned to | Why |
|---|---|---|
| Item name | Left (<) | Names are read from the left; letters start at the same point |
| Quantity, price, amount | Right (>) | The ones digits and the decimal points come one under another |
| Title | Center (^) | It sits symmetrically at the top of the receipt |
If you want the empty space filled with a character other than a space, you write that character before the alignment sign. :=^24 reads: "a field of 24 characters, center, fill the empty space with =". :.<12 means "12 characters, push left, fill the empty space with dots"; this is how the "Latte......4.25" look of menus is made. The fill character must be a single character and is always written together with an alignment sign.
On a receipt, the width appears in many places: in the title, in the line, in the columns. If you write 24 everywhere, you have to change every place one by one when you want to widen the receipt, and if you forget one, the receipt breaks. Instead, you can keep the width in a variable. When the width comes from a variable, you write it inside curly braces too: f"{'RECEIPT':-^{width}}". The outer curly braces calculate the value, and the inner curly braces calculate the width. This way you change the size of the receipt from a single line.
Example 2: Menu and title
print(f"{'CORNER CAFÉ':=^24}") print(f"{'Latte':.<12}{4.25:>8.2f}") print(f"{'Cookie':.<12}{2.00:>8.2f}") width = 20 print(f"{'RECEIPT':-^{width}}")
Output======CORNER CAFÉ=======
Latte....... 4.25
Cookie...... 2.00
------RECEIPT-------CORNER CAFÉ is eleven characters and the field is 24, so 13 characters are left. 13 cannot be split into two equal parts, so there are 6 equals signs on the left and 7 on the right: when the number of empty places is odd, the extra character goes to the right. The same happened on the last line: RECEIPT is seven characters, and of the remaining 13, 6 are on the left and 7 on the right.
In the block below you see the same name in three alignments. The vertical bars show the boundaries of the field. First look at where the empty space goes with short names, then choose the long name and see the field overflow.
How does the same name look in three different alignments? What happens when you choose the long name?
Pick a value; predict the output first, then look.
1item = "Latte"2print(f"|{item:<10}|")3print(f"|{item:^10}|")4print(f"|{item:>10}|")
|Latte | | Latte | | Latte|
Faded lines didn't run with this value. The vertical bars show the boundary of the field. < pushes the name left and fills the remaining space on the right with spaces, > does the opposite, and ^ splits the space between both sides (with an odd number of spaces, the extra goes to the right). The 17-letter name does not fit in the 10-character field: Python does not cut the name, it widens the field; all three lines look the same and the column breaks.
In number columns, alignment and number format work together. In the block below the amount has a different number of digits each time. The square brackets again show the boundary of the field. Choose the values in turn and watch the comma and the decimal point stay in the same column.
How does the column behave when the number of digits in the amount changes?
Pick a value; predict the output first, then look.
1amount = 852print(f"[{amount:>12,.2f}]")
[ 85.00]
Faded lines didn't run with this value. >12,.2f combines four requests: a field of 12 characters, push right, separate thousands with a comma, write two places after the decimal point. As the number grows, the space on the left shrinks but the decimal point always stays in the same place; that is why amounts written one under another are easy to compare. 1,250,000.00 is exactly 12 characters, so no space is left at all.
So far you have printed formatted lines directly with print. But every line of the receipt has the same pattern: item, quantity, unit price, amount. It makes sense to put this pattern in a function. The question is: should the function print the line or return it? In lesson 14 you saw the difference between print and return. A function that prints throws the line onto the screen and leaves you with nothing (it returns None). A function that returns gives you the line as a string. You can use the string you hold wherever you want: add it to the receipt, put it in the report, measure its length, or test it with assert receipt_line("Water", 1, 0.75) == "..." as in lesson 19. A line already printed on the screen can be neither tested nor joined.
Example 3: The function that returns a receipt line
def receipt_line(item, qty, price): # Item 10 left, qty 3 right, unit price 6 right, amount 9 right return f"{item:<10}{qty:>3} x {price:>6.2f}{qty * price:>9.2f}" print(receipt_line("Latte", 2, 4.25)) print(len(receipt_line("Latte", 2, 4.25)))
OutputLatte 2 x 4.25 8.50
31Calculate the length of the line: the item field is 10, the quantity field 3, the x in between is 3 characters, the price field 6, and the amount field 9; total 31. len also said 31. Because every line has the same width, if you make the title and the line 31 characters too, the receipt becomes a perfect rectangle.
Follow the code below step by step. Notice that on the two lines where the function is called nothing is written on the screen; instead, a string is put into each of the top and bottom boxes. Writing to the screen happens only in the last two print lines.
Run the code line by line: see which line runs next, the variable boxes and the output.
def receipt_line(item, qty, price): line = f"{item:<10}{qty:>3} x {price:>6.2f}" return line top = receipt_line("Latte", 2, 4.25) bottom = receipt_line("Water", 1, 0.75) print(top) print(bottom)
Now that you can return lines, you need to join them. To open a new line inside a string, you write \n: "Corner\nCafé" appears on the screen as two lines. For a tab there is \t, but because the width of a tab changes with the environment, a format specifier is more reliable for aligning columns. You write these characters in code with two signs (a backslash and a letter), but inside the string each one is a single character. Test this yourself.
What does this code print?
text = "Port\nAlder" print(len(text))
Writing a long multi-line string with \n makes it hard to read. Instead you can use triple quotes ("""): a string that starts with triple quotes continues until it sees triple quotes again, and keeps the line breaks in between exactly as they are. If you put an f before the triple quotes, the curly braces inside work too. This way the whole receipt becomes a single string, and a function can return it.
Example 3 (continued): The whole receipt
def receipt_line(item, qty, price): return f"{item:<10}{qty:>3} x {price:>6.2f}{qty * price:>9.2f}" def receipt(title, line1, line2, total): # 1. Title in the middle, 2. two item lines, 3. a line, 4. the total return f"""{title:=^31} {line1} {line2} {'-' * 31} {'TOTAL':<22}{total:>9.2f}""" latte = receipt_line("Latte", 2, 4.25) brownie = receipt_line("Brownie", 3, 3.75) print(receipt("CORNER CAFÉ", latte, brownie, 19.75))
Output==========CORNER CAFÉ==========
Latte 2 x 4.25 8.50
Brownie 3 x 3.75 11.25
-------------------------------
TOTAL 19.75This is the target output at the start of the lesson. On the TOTAL line we used 22 + 9 = 31 characters, so the last digit of the total ended in the same column as the other amounts. In older Python code you may see the "{}".format(x) method or the "%d" % x syntax doing the same job; both work, but in new code the f-string is shorter and more readable.
Now it is your turn. In the code below, two functions are ready. First run it as it is. Then add a line of 12 Cookie items to the receipt (unit price 2.00): did the amount 24.00 come out, did the columns break? Do not forget to update the total too. Finally, try tying every place where 31 appears to a width variable.
Try it now· not graded; doesn't affect progress
Let us also correct a common misconception here: the thought that "if the function writes the line to the screen, the job is done". Writing to the screen is only the last step of the job. You write the function that returns the line once, and you use the same function in the receipt, in the report, and in the test. In the exercises, the check will therefore look at the string your function returns.
Formatting is not specific to café receipts. A supplier in Europe may want invoice amounts in the European layout (1.234,50). Python's format specifier produces the US layout; to switch to the European layout you need to swap the comma and the decimal point. Order matters a lot here: if you first turn the points into commas, then when you turn the commas into points, the commas you just created turn into points too. The solution is to first store the commas in a temporary character that does not appear in the string (X).
Example 4: An amount in the European layout (invoice)
def eu_format(amount): text = f"{amount:,.2f}" text = text.replace(",", "X") text = text.replace(".", ",") text = text.replace("X", ".") return text print(eu_format(1234.5)) print(eu_format(4.25)) print(eu_format(1250000))
Output1.234,50
4,25
1.250.000,00If you skipped the temporary character and did . → , first, then , → ., you would get 1.234.50 for 1234.5: the first step produces 1,234,50, and the second step turns both commas into points. Now put the order of the lines together yourself once.
Put the lines of the eu_format function in the correct order: first format the amount in the US layout, then swap the comma and the decimal point.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The second example outside the café is a bus sign. Hours and minutes always appear with two digits on the screen: 09:05, not 9:5. For this you use zero padding: :02 means "pad with zeros on the left up to two characters". The system sometimes gives the time as the total number of minutes since midnight; you separate the hour and the minute with the // and % operators from lesson 3.
Example 5: Bus sign
hour = 9 minute = 5 print(f"{hour:02}:{minute:02}") total_min = 545 print(f"{total_min // 60:02}:{total_min % 60:02}")
Output09:05
09:05545 minutes divided by 60 gives 9 hours with 5 minutes left over. Because you can write a calculation inside the curly braces and then put the format after it, you did not need separate variables.
Prices often come from a file or a form as a string: "4.25". If you try to format this string directly with :.2f, Python stops:
OutputValueError: Unknown format code 'f' for object of type 'str'The message says: "I do not know the f format for a value of type str." The f format wants a number; digits inside a string do not make it a number. The fix is familiar from lesson 4: before formatting, you convert with float(price) to a float. f"{float('4.25'):>6.2f}" works without trouble and gives 4.25. Remember the other trap from lesson 4 as well: if you forget the f before the quote, Python gives no error and writes the curly braces as they are.
A student club shows its dues collection rate and the cash in the box on a single line. The function that returns the line uses all three formats.
def dues_line(club, cash, rate): return f"{club:<10}{cash:>10,.2f} {rate:>6.1%}" print(dues_line("Chess", 922.5, 0.82)) print(dues_line("Drama", 115.25, 0.4))
OutputChess 922.50 82.0%
Drama 115.25 40.0%Writing receipt numbers one under another with zero padding produces a single string joined with \n.
listing = f"{1:03} Latte\n{2:03} Tea\n{3:03} Water" print(listing) print(listing.count("\n"))
Output001 Latte
002 Tea
003 Water
2The three-line string has two newline characters; the lines are separated by \n, and there is no extra newline at the end of the string.
Formatting a number that arrives as a string. If price = "4.25" and you write f"{price:>6.2f}", you get ValueError: Unknown format code 'f' for object of type 'str'. The right way: f"{float(price):>6.2f}".
Calculating the percentage by hand. If rate = 0.29 and you write f"{rate * 100}%", you see 28.999999999999996% on the screen; the small calculation leftover of floats on a computer shows up. f"{rate:.1f}%" does not do the multiplication, so it gives 0.3%. The right way: f"{rate:.1%}" → 29.0%.
:, thousands separator, :.1% multiply by 100 first and then percent, :03 zero padding; they can be combined (:>12,.2f) and the value in the variable stays the same.< aligns left, > right, ^ center; a character written before the alignment fills the empty space (:=^24); the width can come from a variable ({text:=^{width}}); a long value is not cut, it overflows the field.print a formatted line, return it: you use the same line in the receipt, in the report, and in the test. \n and \t are single characters in a string; a triple-quoted string keeps its line breaks and makes the whole receipt a single string.Next lesson: In the unit task (G5, Caesar cipher) you will use indexes, string methods, and formatting together; then we move on to lists.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
:03 | Pad with zeros on the left up to 3 characters | f"{7:03}" | 007 |
:,.2f | Thousands separator + two decimals | f"{1234.5:,.2f}" | 1,234.50 |
:>12,.2f | 12 characters, right-aligned, separator, two decimals | f"{1234.5:>12,.2f}" | 1,234.50 |