F-strings, or formatted string literals, are a feature in Python that allows for easy and readable string formatting. They were introduced in Python 3.6. The main purposes of f-strings are:
-
Interpolation: You can embed expressions inside string literals, using curly braces
{}. This allows you to include variable values directly within the string.Example:
name = "Alice" greeting = f"Hello, {name}!" -
Readability: F-strings make the code cleaner and more readable compared to older formatting methods (like
%formatting orstr.format()). -
Performance: F-strings are generally faster than other string formatting methods because they are evaluated at runtime and do not require additional function calls.
-
Complex Expressions: You can include more complex expressions inside the curly braces, not just variable names.
Example:
age = 30 message = f"{name} is {age + 1} years old."
In summary, f-strings provide a concise and efficient way to create formatted strings in Python.
