8

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) + "!")
3
  • 1
    format exists in 2.7 Commented Apr 16, 2019 at 13:22
  • Possible duplicate of Python string formatting: % vs. .format Commented Apr 16, 2019 at 13:23
  • a = 21 + 21 print("the answer is {}".format(a)) Commented Apr 16, 2019 at 13:25

5 Answers 5

13

Using format:

print("the answer is {} !".format(21 + 21))
Sign up to request clarification or add additional context in comments.

Comments

6

There are two ways

>>> "The number is %d" % (21+21)
'The number is 42'
>>> "The number is {}".format(21+21)
'The number is 42'

Comments

5

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'

Comments

4

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))

Comments

1

The simple-fstring library may be an alternative for you!

Installation

pip install simple-fstring

Usage

from fstring import f
print f("The answer is ${21 + 21}!")

Output:

The answer is 42!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.