In Python, you can use curly braces ({}
) to format strings more efficiently. This technique is known as "f-strings" (formatted string literals) or "string interpolation". F-strings allow you to embed expressions directly within a string, making it easier to construct dynamic and readable strings.
To use f-strings, simply prefix the string with the letter f
or F
, and then enclose the expressions you want to include within curly braces:
name = "LabEx"
age = 5
print(f"My name is {name} and I am {age} years old.") ## Output: "My name is LabEx and I am 5 years old."
Within the curly braces, you can use various formatting options to control the appearance of the embedded expressions:
pi = 3.14159
print(f"The value of pi is {pi:.2f}") ## Output: "The value of pi is 3.14"
number = 1234
print(f"The number is {number:,}") ## Output: "The number is 1,234"
F-strings also support more advanced formatting techniques, such as alignment, padding, and value conversion:
name = "LabEx"
age = 5
print(f"{name:>20} is {age:03d} years old.") ## Output: " LabEx is 005 years old."
By mastering the use of curly braces in string formatting, you can create more dynamic and expressive strings in your Python code.