1

What are the respective advantages of the below syntaxes?

I don't really understand why to use one or the other.

# 1
print("The total is "+ str(totalBill))

# 2
print(f"The total is {totalBill}")

# 3
print("The total is {}.".format(totalBill))
khelwood
  • 55,782
  • 14
  • 81
  • 108
William
  • 39
  • 2

1 Answers1

3

While all of them could achieve the same thing in python for printing this, the f-string formatting in the second process is the latest one introduced in python 3.6 - PEP 498. The first method is simply adding one string to another string and then printing the conjoined string. str.format() in the third process was introduced in Python 2.6. str.format() was an improvement done over the previous %-formatting. The new f-string formatting is again improved over str.format() method. For printing lots of parameters, the str.format() becomes quite verbose. Also f-string usage is faster compared to str.format() method as well as the old %-formatting. F-strings are evaluated at runtime rather than constant values. At run time, the expressions inside the curly braces of f-string are evaluated in their own scope and then put together in the returning string. Process #2 where F-string literals are used, is advised over str.format() method as well as the joining strings process.

Here is a comparison :

from timeit import timeit as t
t("""totalBill = 100
print("The total is "+str(totalBill))""", number=10000)
# 7.241250243259877 seconds

t("""totalBill = 100
print(f"Total bill is {totalBill})""", number=10000)
# 3.1151810346903517 seconds
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • @William: see also [here](https://stackoverflow.com/questions/40714555/python-string-formatting-is-more-efficient-than-format-function) on performance of the different methods. Might be significant, depending on how many strings you format. – FObersteiner Aug 31 '19 at 17:10