Skip to main content

How to format a string in Python using placeholders

How to format a string in Python using placeholders.

Here's a step-by-step tutorial on how to format a string in Python using placeholders:

  1. Start by defining a string that you want to format. Let's say we have the following string:

    my_string = "Hello, {}!"
  2. To insert values into the placeholders, use the .format() method on the string. Inside the parentheses of the .format() method, pass the values you want to insert in the placeholders. For example, let's insert the name "John" into the placeholder:

    formatted_string = my_string.format("John")
  3. The formatted string will replace the placeholder {} with the value you provided. In this case, the formatted_string will be:

    Hello, John!
  4. You can also have multiple placeholders in a string and provide multiple values to format them. Let's take an example:

    my_string = "My name is {}, and I am {} years old."
    name = "Emma"
    age = 25
    formatted_string = my_string.format(name, age)
  5. In this case, the formatted_string will be:

    My name is Emma, and I am 25 years old.
  6. You can also use placeholders with specified indexes to format the string. This allows you to provide values in any order you want. Let's modify the previous example:

    my_string = "My name is {1}, and I am {0} years old."
    name = "Emma"
    age = 25
    formatted_string = my_string.format(age, name)
  7. Now, the formatted_string will be the same as before:

    My name is Emma, and I am 25 years old.
  8. Placeholder formatting can be customized further by specifying format specifiers. For example, you can control the width, precision, alignment, and data type of the values being inserted. Let's consider an example:

    my_string = "The price is ${:.2f}"
    price = 19.99
    formatted_string = my_string.format(price)
  9. In this case, the formatted_string will be:

    The price is $19.99
  10. The :.2f format specifier ensures that only two decimal places are displayed after the decimal point.

That's it! You have now learned how to format a string in Python using placeholders. Feel free to experiment with different placeholders and format specifiers to suit your needs.