Python String Formatting: % Placeholders vs f‑Strings Explained
This tutorial walks through Python's two main string formatting techniques—classic % placeholders and modern f‑strings—detailing specifiers like %d, %f, %s, %.2f, and providing concrete code examples that show how each method formats name, age, and salary variables.
The note emphasizes that consistent practice is essential when learning Python from scratch.
It introduces two ways to format strings in Python: using the classic % placeholder syntax and the modern f‑string syntax.
For the % method, the article lists common specifiers: %d for integers, %f for floating‑point numbers, %s for strings, and %.2f to limit a float to two decimal places.
Example variables are defined:
name = "张三"
age = 21
money = 12345.321Using % formatting, the following statements produce formatted output:
print("我的姓名是:%s,年龄是:%d,收入是:%f" % (name, age, money))
print("我的姓名是:%s,年龄是:%d,收入是:%.2f" % (name, age, money))
print("我的姓名是:%s,年龄是:%d,收入是:%.3f" % (name, age, money))With f‑strings, the same information is printed more concisely:
print(f"我的姓名是:{name},年龄是{age},收入是{money}")The article then shows the resulting output for each method, demonstrating that the % approach prints the full float by default, while formatting specifiers can control precision, and that f‑strings produce the same values with simpler syntax.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
