Skip to main content

Command Palette

Search for a command to run...

Day-28 f-strings

Updated
3 min read
Day-28 f-strings
C
I am Data Science student, has a little bit knowledge on Web Development. I also love writing and editing as my hobby. Passionate to explore the world.

String formatting in python

String formatting can be done in python using the format method.

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

f-strings in python

It is a new string formatting mechanism introduced by the PEP 498. It is also known as Literal String Interpolation or more commonly as F-strings (f character preceding the string literal). The primary focus of this mechanism is to make the interpolation easier.

When we prefix the string with the letter 'f', the string becomes the f-string itself. The f-string can be formatted in much same as the str.format() method. The f-string offers a convenient way to embed Python expression inside string literals for formatting.

Example

val = 'Geeks'  
print(f"{val}for{val} is a portal for {val}.")  
name = 'Tushar'  
age = 23  
print(f"Hello, My name is {name} and I'm {age} years old.")  

Output:

Hello, My name is Tushar and I'm 23 years old.

In the above code, we have used the f-string to format the string. It evaluates at runtime; we can put all valid Python expressions in them.


We can use it in a single statement as well.

Example

print(f"{2 * 30})"  

Output:

60

Practice

letter = "Hey my name is {1} and I am from {0}"
country = "India"
name = "Harry"

print(letter.format(country, name))
print(f"Hey my name is {name} and I am from {country}")
print(f"We use f-strings like this: Hey my name is {{name}} and I am from {{country}}")
price = 49.09999
txt = f"For only {price:.2f} dollars!"
print(txt)
# print(txt.format())
print(type(f"{2 * 30}"))

Output:

Hey my name is Harry and I am from India
Hey my name is Harry and I am from India
We use f-strings like this: Hey my name is {name} and I am from {country}
For only 49.10 dollars!
<class 'str'>

Explanation:

  • letter.format(country, name)

    • {0}country"India"

    • {1}name"Harry"

    • Output: Hey my name is Harry and I am from India

  • f"Hey my name is {name} and I am from {country}"

    • Direct variable interpolation using f-strings.
  • Double braces {{ and }}

    • Used to print literal { and } characters.
  • {price:.2f}

    • Formats the float to 2 decimal places.

    • 49.09999 becomes 49.10.

  • f"{2 * 30}"

    • Evaluates the expression 2 * 3060.

    • An f-string always returns a string,

100DaysofPython

Part 29 of 35

This series is for beginners in which we explore python language along with how it is used in data science and do some exercises and some python related projects.

Up next

Day 29-Docstrings

Docstrings in python Python docstrings are the string literals that appear right after the definition of a function, method, class, or module. Example def square(n): '''Takes in a number n, return