Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) + "!")
like image 630
Marius Illmann Avatar asked Jun 04 '26 12:06

Marius Illmann


2 Answers

Using format:

print("the answer is {} !".format(21 + 21))
like image 197
VnC Avatar answered Jun 07 '26 08:06

VnC


There are two ways

>>> "The number is %d" % (21+21)
'The number is 42'
>>> "The number is {}".format(21+21)
'The number is 42'
like image 41
Shuvojit Avatar answered Jun 07 '26 08:06

Shuvojit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!