5.1 Ways to Format Strings

A Nicely Rolled-Up Ball of String

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:

  1. Using the %s variable

    These variables can be used to perform string formatting. Let’s start with the %s variable first; also, I have created a variable name that stores my first name Kevin. 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 of name where the %s is.

  2. Using Python’s .format()

    Again, I have a variable name that 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.

  3. Using f

    I 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

  1. Note that whatever you type inside the curly braces will be evaluated as just vanilla Python code!↩︎