简体   繁体   中英

Python3 f string alternativ in Python2

Mostly i work with Python3. There can i write this

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

output: the answer is 42 ! But in Python 2 f strings not exist. So is this the best way ?

print("the answer is " + str(21 + 21) + "!")

使用format

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

There are two ways

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

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

You can use:

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM