ScanSkill

f-string

In Python 3.6+, formatted string i.e. f-string is used to make string interpolation simpler. Which definitely makes it possible to insert variables or expressions into strings in an easier and more convenient way.

To create f-sting, letter "f" is used as a prefix to the string. It's similar to str.format().

Syntax

f"<string with variables>"
f"<string with arbitrary Python expression>"

Here, A letter or character f is added in front of a string. Inside string, you can add any number of variables or arbitrary expressions wrapped around curly braces {}.

Examples

  • With single variable
>>> name = "Sagar"
>>> print(f"My name is {name}")
My name is Sagar
  • With multiple variables
>>> name = "Sagar"
>>> platform = "scanskill.com"
>>> print(f"Hello, I'm {name}. I write articles on {platform}.")
Hello, I'm Sagar. I write articles on scanskill.com.
  • With arbitrary expressions
>>> print(f"The output of 5*5 is {5*5}")
The output of 5*5 is 25
  • With numbers
>>> float_num1 = 13.1313
>>> print(f"The number is: {float_num1:.2f}")
The number is 13.13