Saturday, March 29, 2025

What is print(f"...") in Python

A formatted string literal or f-string is a string literal that is prefixed with f or F. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. It was introduced in Python 3.6 and allows for a more readable and concise way of formatting strings compared to older methods like using str.format() or concatenation.



Here's an example:

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

Explanation:
  1. f"..." tells Python to treat the string as an "f-string" (formatted string).
  2. Inside the curly braces {}, you can insert variables, expressions, or calculations.
  3. When you run this code, Python evaluates the expressions inside the braces and substitutes them with their values.

The output would be:

My name is Skptricks and I am 34 years old.


F-strings are a powerful and efficient way to include dynamic values in strings.


No comments:

Post a Comment