How to print like printf in Python3?

前端 未结 9 2030
粉色の甜心
粉色の甜心 2020-11-29 16:52

In Python 2 I used:

print \"a=%d,b=%d\" % (f(x,n),g(x,n))

I\'ve tried:

print(\"a=%d,b=%d\") % (f(x,n),g(x,n))
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 17:13

    Python 3.6 introduced f-strings for inline interpolation. What's even nicer is it extended the syntax to also allow format specifiers with interpolation. Something I've been working on while I googled this (and came across this old question!):

    print(f'{account:40s} ({ratio:3.2f}) -> AUD {splitAmount}')
    

    PEP 498 has the details. And... it sorted my pet peeve with format specifiers in other langs -- allows for specifiers that themselves can be expressions! Yay! See: Format Specifiers.

提交回复
热议问题