F String in Python

What are f-strings?

F-strings are formatted string literals, which were added to Python 3.6. They allow expressions to be embedded inside string literals using curly braces {}. F-strings are denoted by a prefix of either the letter f or F. This makes string interpolation easier and more readable.

Syntax

f"string with {expression}"
  • f: Denotes the string as an f-string.
  • {}: Contains Python expressions that will be evaluated and replaced with their value.

Key Features of f-strings

1. Basic Example

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

Output:

My name is Alice and I am 25 years old.

Here:

  • {name} is replaced by the value of the variable name.
  • {age} is replaced by the value of the variable age.

2. Expressions Inside f-strings

You can use any valid Python expression inside {}.

Examples:

1. Arithmetic operations:

print(f"5 + 2 = {5 + 2}")

Output:

5 + 2 = 7

2. Method calls:

print(f"Hello, {'world'.upper()}!")

Output:

Hello, WORLD!

3. Conditional expressions:

is_logged_in = True
print(f"User status: {'Logged In' if is_logged_in else 'Logged Out'}")

Output:

User status: Logged In

3. Type Conversion

You may use the following conversion flags in the curly brackets:

  • !s: Use str() on the value to render it as a string.
  • !r: Convert value to its printable representation (using repr()).
  • !a: Evaluates ascii() on the input.

Example:

value = "Hello\nWorld"
print(f"String: {value!s}")
print(f"Representation: {value!r}")
print(f"ASCII: {value!a}")

Output:

String: Hello
World
Representation: 'Hello\nWorld'
ASCII: 'Hello\nWorld'

4. Formatting Numbers

You can control the formatting of numbers with format specifications inside {}.

Examples:

1. Fixed decimal places:

pi = 3.14159
print(f"Value of pi: {pi:.2f}")

Output:

Value of pi: 3.14

2. Add leading zeros:

num = 42
print(f"Number: {num:05}")

Output:

Number: 00042

3. Add commas for large numbers:

large_number = 1000000
print(f"Formatted: {large_number:,}")

Output:

Formatted: 1,000,000

4. Percentage formatting:

success_rate = 0.85
print(f"Success rate: {success_rate:.1%}")

Output:

Success rate: 85.0%

5. Multiline f-strings

You can use triple quotes to create multiline f-strings.

Example:

name = "Alice"
age = 25
message = f"""
Name: {name}
Age: {age}
"""
print(message)

Output:

Name: Alice
Age: 25

6. Using f-strings with Dictionaries

You can directly access dictionary keys inside f-strings.

Example:

person = {"name": "Bob", "age": 30}
print(f"Name: {person['name']}, Age: {person['age']}")

Output:

Name: Bob, Age: 30

7. Using f-strings with Functions

You can call functions inside f-strings.

Example:

def square(num):
    return num * num

print(f"The square of 5 is {square(5)}")

Output:

The square of 5 is 25

8. Escaping Braces

If you need to include curly braces {} as part of your string, double them {{ and }}.

Example:

value = 42
print(f"The value is {{value}}")

Output:

The value is {value}

9. f-strings vs Other String Formatting Methods

Here’s how f-strings compare with older methods of string formatting:

a. % Formatting (Old Style):

name = "Alice"
print("Hello, %s!" % name)

b. .format() Method:

name = "Alice"
print("Hello, {}!".format(name))

c. f-strings (Modern Way):

name = "Alice"
print(f"Hello, {name}!")

f-strings are faster and more concise than both % formatting and .format().

Limitations of f-strings

  1. Static strings only: You can’t use an f-string for dynamically created string literals, such as loaded from a file.
  2. Available in Python 3.6+: If you’re using an older version of Python, f-strings won’t work.
  3. Single Expression in {}: Every {} shall contain a single valid Python expression.