Python > Core Python Basics > Input and Output > Printing Output (print())
Formatted Output with f-strings
This snippet demonstrates how to use f-strings (formatted string literals) in Python to create more readable and dynamic output. F-strings allow you to embed expressions inside string literals.
f-string Example
f-strings are created by prefixing a string literal with `f` or `F`. Inside the string, you can embed expressions by enclosing them in curly braces `{}`. The expressions are evaluated at runtime, and their values are inserted into the string. You can also use format specifiers inside the curly braces to control how the values are displayed (e.g., `:.2f` for formatting a float to 2 decimal places).
name = "Bob"
age = 25
print(f"My name is {name} and I am {age} years old.")
pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}") # Format to 2 decimal places
Concepts Behind the Snippet
f-strings provide a concise and readable way to format strings. They are generally more efficient than other string formatting methods like `str.format()` or `%`-formatting. They are evaluated at runtime, meaning the expressions inside the curly braces are calculated when the string is used.
Real-Life Use Case
Consider a program that generates reports. You can use f-strings to easily insert data like dates, names, and calculated values into report templates, making the reports dynamic and personalized.
Best Practices
Use descriptive variable names to improve readability. Choose appropriate format specifiers to display values in the desired format (e.g., dates, currencies, percentages). Be mindful of potential security risks if the expressions inside the f-string come from untrusted sources (e.g., user input), as they can execute arbitrary code.
When to use them
Use f-strings whenever you need to create strings that combine literal text with the values of variables or expressions. They are particularly useful for generating formatted output, creating dynamic messages, and debugging.
Alternatives
Alternatives to f-strings are the older `.format()` method and %-formatting. F-strings are generally preferred for their readability and performance.
Pros
Readability: f-strings are very easy to read and understand.
Conciseness: They reduce the amount of code needed for string formatting.
Performance: They are generally faster than other formatting methods.
Cons
Security: Evaluating expressions from untrusted sources can be a security risk.
Python Version: f-strings were introduced in Python 3.6, so they are not available in older versions.
FAQ
-
Can I use f-strings with multiline strings?
Yes, you can use f-strings with multiline strings. Just prefix the multiline string with `f` or `F`. -
How do I escape curly braces in an f-string?
To include literal curly braces in an f-string, double them: `{{` and `}}`. For example, `print(f"{{This is inside curly braces}}")` will print "{This is inside curly braces}".