5.1 Ways to Format Strings
Like I mentioned earlier, I currently know of three different ways to accomplish the same action:
Using the
%s
variableThese variables can be used to perform string formatting. Let’s start with the
%s
variable first; also, I have created a variablename
that stores my first nameKevin
. Using the same variable, I can re-write the code snipper shown earlier as:= "Kevin" name 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 ofname
where the%s
is.Using Python’s
.format()
Again, I have a variable
name
that performs the same function. Here’s how I would do it this time:= "Kevin" name 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
f
I can also do string formatting like so using
f
. It’s by far my preferred way of doing things:= "Kevin" name 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!↩︎