3

i'm learning python from a book that i bought in 2017 and from a online course at the same time.

The book says that i should format the string like this example;

print("Guess number %d of %d" % (variable1, variable2))

But the online course says that i should format this way;

print("Guess number {} of {}".format(variable1, variable2))

Which one should i use for today programming standards?

CDJB
  • 13,204
  • 5
  • 27
  • 47

2 Answers2

4

Well, from Python 3.6, you can use f-strings:

print(f"Guess number {variable1} of {variable2}")
CDJB
  • 13,204
  • 5
  • 27
  • 47
  • 1
    curiosity. There is one other major difference too, isn’t there? an f-string is built and replaced on the spot, with local variables. whereas a %-based, or a $-based, template can be saved and used elsewhere/later. I ask that because I have code that relies heavily on building complex templates and passing them around as parameters. So I’ve always seen f-strings as nice (and fast) but not always flexible enough. – JL Peyret Dec 10 '19 at 01:11
  • @JLPeyret Indeed, though there are some options for implementing this functionality - see [this question](https://stackoverflow.com/q/42497625/12366110). – CDJB Dec 10 '19 at 08:20
1

I'd predict the use are f-strings are aimed at readability. That said, i would say the real answer is which ever one is more readable in your function or whatever.

Jay_jen
  • 44
  • 5