Welcome aboard! Today, we're venturing into the world of string formatting and interpolation in Python. These operations enable dynamic string construction, which streamlines coding in Python. Picture yourself compiling daily astronaut logs; these techniques allow you to create a template and fill in the variable part each time. In this lesson, we'll:
- Examine string formatting using the
%operator. - Learn about the
.format()method for string interpolation. - Explore Python's
f-Stringsfor string interpolation.
Let's blast off!
String formatting and interpolation replace the need for manual string construction, thereby enhancing code readability. Take this example, for instance:
In this case, we're manually constructing the string by combining several parts — it's a bit clunky, isn't it? Let's make this simpler with string formatting and interpolation.
The % operator in Python enables the substitution of parts of a string, simplifying the process:
Here, %d and %s are placeholders for an integer and a string, which are replaced by day and message in the output.
There are several main types you might need to use together with %:
%d- number%s- string%f- float
The .format() method provides greater control over string interpolation. Let's rewrite the previous log entry:
With the .format() method, you can use variable names directly in placeholders, which improves readability.
