What is usage of the last comma in this code?

前端 未结 2 1831
情歌与酒
情歌与酒 2021-01-17 11:54
for x in range(1, 11):
     print repr(x).rjust(2), repr(x*x).rjust(3),
     # Note trailing comma on previous line
     print repr(x*x*x).rjust(4)

相关标签:
2条回答
  • 2021-01-17 12:11

    A comma at the end of a print statement prevents a newline character from being appended to the string. (See http://docs.python.org/reference/simple_stmts.html#the-print-statement)

    In your tweaked code:

    for x in range(1, 11):
        print repr(x).rjust(2), repr(x*x).rjust(3),
        # Note trailing comma on previous line
        repr(x*x*x).rjust(4)
    

    the last line simply becomes an unused expression because Python statements are generally separated by line breaks. If you added a backslash (\) -- the Python line continuation character -- to the end of the line of the print statement and removed the comment, then the repr(x*x*x).rjust(4) would be appended to the print statement.

    To be more explicit:

    print repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)
    

    and

    print repr(x).rjust(2), repr(x*x).rjust(3), \
    repr(x*x*x).rjust(4)
    

    are equivalent, but

    print repr(x).rjust(2), repr(x*x).rjust(3),
    repr(x*x*x).rjust(4)
    

    is not. This oddness of the print statement is one of the things they fixed in Python 3, by making it a function. (See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function)

    0 讨论(0)
  • 2021-01-17 12:14

    It stops print from printing a newline at the end of the text.

    As Dave pointed out, the documentation in python 2.x says: …. "A '\n' character is written at the end, unless the print statement ends with a comma."

    UPDATE:

    The documentation of python 3.x states that print() is a function that accepts the keyword argument end which defaults to a newline, \n.

    0 讨论(0)
提交回复
热议问题