Strings & f-strings
字符串与 f-string
A string is a sequence of characters. f-strings — Python's modern way to weave values into text — are the only string formatting you really need in this course.
Strings: text in quotes
A string is any sequence of characters wrapped in quotes.
Python accepts either single quotes '...' or double quotes
"..." — pick one and be consistent. Use the other style when the
string itself contains a quote.
+ glues strings, * repeats them
The same + you use for numbers also concatenates
strings — it joins them end-to-end. The * operator repeats
a string. Both operands of + must be strings, though.
f-strings: the right way to build text
An f-string is a string literal with the letter f
in front. Inside it, anything in {} is treated as a Python
expression and replaced with its value at runtime. This is by far the most
common way to format text in modern Python.
Inside the braces you can put any expression — not just a single variable:
The three formatting styles you may see
You'll find old code that uses %-formatting or
.format(). They still work, but for this course, write f-strings.
Check yourself
What does this print? greeting = f"Hi {name.upper()}" print(greeting) — given name = "ada"
Check yourself
Which of these correctly puts the value of `qty` into the message?
Now you try
The exercise file 03-strings-and-fstring.py in WolfCode asks
you to write a function build_greeting(name, age) that returns
a greeting in the f-string style. The tests check both names and ages, so
your function has to work for any input — don't hardcode "Alice".