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:
-
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." -
str.format()method:name = "Alice" age = 30 formatted_string = "My name is {} and I am {} years old.".format(name, age) -
Percent formatting (older style):
name = "Alice" age = 30 formatted_string = "My name is %s and I am %d years old." % (name, age) -
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 -
Using
str.format()with named placeholders:formatted_string = "My name is {name} and I am {age} years old.".format(name="Alice", age=30) -
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.
