How to print like printf in Python3?

前端 未结 9 1980
粉色の甜心
粉色の甜心 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:06

    The most recommended way to do is to use format method. Read more about it here

    a, b = 1, 2
    
    print("a={0},b={1}".format(a, b))
    
    0 讨论(0)
  • 2020-11-29 17:06
    print("Name={}, balance={}".format(var-name, var-balance))
    
    0 讨论(0)
  • 2020-11-29 17:08

    Simple printf() function from O'Reilly's Python Cookbook.

    import sys
    def printf(format, *args):
        sys.stdout.write(format % args)
    

    Example output:

    i = 7
    pi = 3.14159265359
    printf("hi there, i=%d, pi=%.2f\n", i, pi)
    # hi there, i=7, pi=3.14
    
    0 讨论(0)
  • 2020-11-29 17:11

    Because your % is outside the print(...) parentheses, you're trying to insert your variables into the result of your print call. print(...) returns None, so this won't work, and there's also the small matter of you already having printed your template by this time and time travel being prohibited by the laws of the universe we inhabit.

    The whole thing you want to print, including the % and its operand, needs to be inside your print(...) call, so that the string can be built before it is printed.

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

    I have added a few extra spaces to make it clearer (though they are not necessary and generally not considered good style).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 17:21

    In Python2, print was a keyword which introduced a statement:

    print "Hi"
    

    In Python3, print is a function which may be invoked:

    print ("Hi")
    

    In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side.

    So, your line ought to look like this:

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

    Also, the recommendation for Python3 and newer is to use {}-style formatting instead of %-style formatting:

    print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))
    

    Python 3.6 introduces yet another string-formatting paradigm: f-strings.

    print(f'a={f(x,n):d}, b={g(x,n):d}')
    
    0 讨论(0)
提交回复
热议问题