Marius Illmann
Marius Illmann

Reputation: 352

Python 3 f-string alternative in Python 2

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) + "!")

Upvotes: 8

Views: 21238

Answers (5)

VnC
VnC

Reputation: 2026

Using format:

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

Upvotes: 13

Hen.fang
Hen.fang

Reputation: 19

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!

Upvotes: 1

TheDarkKnight
TheDarkKnight

Reputation: 421

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

Upvotes: 4

RinSlow
RinSlow

Reputation: 139

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'

Upvotes: 5

Shuvojit
Shuvojit

Reputation: 1470

There are two ways

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

Upvotes: 6

Related Questions