What are string formatting options?

0139

In Python, string formatting options allow you to create formatted strings by embedding values within a string. Here are some common methods for string formatting:

  1. f-strings (formatted string literals) (Python 3.6+):

    name = "Alice"
    age = 30
    formatted_string = f"My name is {name} and I am {age} years old."
  2. str.format() method:

    name = "Alice"
    age = 30
    formatted_string = "My name is {} and I am {} years old.".format(name, age)
  3. Percent formatting (older style):

    name = "Alice"
    age = 30
    formatted_string = "My name is %s and I am %d years old." % (name, age)
  4. Using format specifiers:
    You can control the width, precision, and alignment of the output using format specifiers:

    value = 123.456
    formatted_string = "Value: {:.2f}".format(value)  # Output: Value: 123.46
  5. Using str.format() with named placeholders:

    formatted_string = "My name is {name} and I am {age} years old.".format(name="Alice", age=30)
  6. Padding and alignment:
    You can specify padding and alignment:

    formatted_string = "{:<10} | {:>10}".format("Left", "Right")  # Left-aligned and right-aligned

These methods provide flexibility in formatting strings to meet various output requirements.

0 Comments

no data
Be the first to share your comment!