All Posts

F-strings in Python

F-strings in Python

String formatting is a common task in Python programming, where you want to insert variables or expressions into a string. Over the years, Python has evolved in how it handles string formatting. One of the most modern and recommended ways to format strings is using F-strings. Introduced in Python 3.6, F-strings offer a clean, fast, and readable way to embed expressions directly inside string literals.

F-strings, or formatted string literals, are created by prefixing a string with the letter f or F. Inside the string, you can include Python expressions within curly braces {}, and they will be evaluated at runtime.

String Formatting Using F-strings

F-strings allow you to include not just variables, but also expressions and function calls directly within the curly braces:

x = 10
y = 5
result = f"The sum of {x} and {y} is {x + y}"
print(result)

Output:

The sum of 10 and 5 is 15

Example

name = "Alice"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)

Output:

My name is Alice and I am 30 years old.

Python F-Strings Demo Program

You can also format numbers:

pi = 3.14159
formatted = f"Value of pi to 2 decimal places: {pi:.2f}"
print(formatted)

Output:

Value of pi to 2 decimal places: 3.14

Examples

language = "Python"

version = 3.12

print(f"{language} version is {version}")

print(f"Uppercase: {language.upper()}")

print(f"Next year you will be {age + 1}")

Comparison of Formatting Methods

Method Example Description
% Operator "Name is %s" % name Old-style formatting, less readable for complex expressions.
str.format() "Name is {}".format(name) More flexible than %, but more verbose than F-strings.
F-string f"Name is {name}" Modern and preferred. Cleaner syntax and better performance.

Benefits of F-strings

  • Readable: Cleaner and more natural syntax.
  • Efficient: Faster than older formatting methods.
  • Flexible: Supports expressions, function calls, and formatting in one place.
  • Concise: No need to reference variables separately; embed directly.

In summary, Python F-strings are a powerful and modern way to handle string formatting. They are more readable, concise, and often faster than the older formatting approaches. If you’re using Python 3.6 or later, F-strings should be your default choice for string formatting tasks.

 

Python Tutorials

Python Tutorial on this website can be found at: