DMarlon Studio

Lesson 4 · 4 of 20

Strings and f-strings · Python

Work with text in Python: join and repeat strings, count characters with len(), read positions and format values with f-strings.

Python · Strings and f-strings in DMarlon Studio: the example's code and its output in the terminal

A string (str) is text between quotes, single or double: "Ada" and 'Lovelace' work the same. + joins them (first + " " + last gives Ada Lovelace) and * repeats them: "=" * 20 draws a line of twenty signs.

len() counts the characters, spaces included: Ada Lovelace has 12. Each character has a position (an index) starting at 0: first[0] is A, and negative positions count from the end, so last[-1] is the last letter, e.

You cannot join a number to a string with +: Python would stop with an error. Convert it first with str(score), as the first score sentence does.

An f-string is handier: a string with an f in front where values go inside braces, f"{first} scored {score} points.". Any calculation fits inside the braces, such as {score + 5}.

After a colon comes the format: {average:.2f} keeps two decimals (87.46); {first:>8} fills 8 spaces aligned to the right, and {last:<10} fills 10 aligned to the left. The square brackets in the output let you see that padding.

Code · main.py

# Strings are text between quotes, single or double.first = "Ada"last = 'Lovelace'# + joins strings and * repeats them.full = first + " " + lastprint(full)print("=" * 20)# len() counts the characters.print("Characters in the name:", len(full))# Each character has a position, starting at 0.print("Initials:", first[0] + last[0])print("Last letter:", last[-1])# str() turns a number into text so it can be joined.score = 92print(first + " scored " + str(score) + " points.")# An f-string puts values straight into the text with { }.print(f"{first} scored {score} points.")print(f"Next year she wants {score + 5}.")# After a colon you can format: decimals, width, alignment.average = 87.456print(f"Class average: {average:.2f}")print(f"[{first:>8}] [{last:<10}]")

Output · python3 main.py

Ada Lovelace
====================
Characters in the name: 12
Initials: AL
Last letter: e
Ada scored 92 points.
Ada scored 92 points.
Next year she wants 97.
Class average: 87.46
[     Ada] [Lovelace  ]

Key points

  • + joins strings and * repeats them.
  • len() counts characters; text[0] is the first and text[-1] the last.
  • str() turns a number into text.
  • In an f-string, values go inside { }.
  • :.2f gives two decimals; :>8 and :<8 align within 8 spaces.

Exercise

Put your own first and last name in the variables, then print your initials and the length of your full name, centred in 30 spaces with :^30.