5.1 Ways to Format Strings
Figure 5.2: A Nicely Rolled-Up Ball of String
Like I mentioned earlier, I currently know of three different ways to accomplish the same action:
Using the
%svariableThese variables can be used to perform string formatting. Let’s start with the
%svariable first; also, I have created a variablenamethat stores my first nameKevin. Using the same variable, I can re-write the code snipper shown earlier as:name = "Kevin" print("Hello, my name is %s!" % name)The
%s- in essence - works as a placeholder variable for strings. One then enters a%sign to place the value ofnamewhere the%sis.Using Python’s
.format()Again, I have a variable
namethat performs the same function. Here’s how I would do it this time:name = "Kevin" print("Hello, my name is {}!".format(name))If it helps, you can think of the
{}as little “crab pincers” that hold a variable’s value in that location of the string.Using
fI can also do string formatting like so using
f. It’s by far my preferred way of doing things:name = "Kevin" print(f"Hello, my name is {name}")However, I can also do this and its output is2:
print(f"2 + 3 = {2 + 3}")## 2 + 3 = 5
Note that whatever you type inside the curly braces will be evaluated as just vanilla Python code!↩︎