5

Mostly I work with Python 3. There can I write this:

print(f"The answer is {21 + 21}!")

Output:

The answer is 42!

But in Python 2, f-strings do not exist. So is the following the best way?

print("the answer is " + str(21 + 21) + "!")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marius Illmann
  • 302
  • 3
  • 5
  • 14

4 Answers4

10

Using format:

print("the answer is {} !".format(21 + 21))

VnC
  • 1,936
  • 16
  • 26
5

There are two ways

>>> "The number is %d" % (21+21)
'The number is 42'
>>> "The number is {}".format(21+21)
'The number is 42'
Shuvojit
  • 1,390
  • 8
  • 16
3

Actually, you can use the .format() method for readability, and it is the where the f-string comes from.

You can use:

print("the answer is {}!".format(21+21))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheDarkKnight
  • 401
  • 1
  • 4
  • 9
3

You can use the fstring library

pip install fstring

>>> from fstring import fstring as f
>>> a = 4
>>> b = 5
>>> f('hello result is {a+b}')
u'hello result is 9'
RinSlow
  • 91
  • 1
  • 3