在 python 3.4.3 上使用“%”符号打印功能时语法无效

Invalid syntax when using "%" sign on print function on python 3.4.3

我正在尝试通过以下方式在 python 3.4.3 上打印内容:

a=1    
b=2
print("text text %2d text text %2d", %(a,b))

但是当我尝试 运行 这个简单的代码时,它恰好在最后一个“%”符号上方出现了一个标记 "invalid syntax":

  File "<stdin>", line 1
    print("text text %2d text text %2d", %(a,b))
                                         ^
SyntaxError: invalid syntax

您需要删除逗号:

print("text text %2d text text %2d", %(a,b))
#                                  ^

% 是一个二元运算符,它适用于两个输入。这些输入是字符串和 (a, b) 元组:

print("text text %2d text text %2d" % (a,b))

您的字符串后不需要逗号:

print("text text %2d text text %2d" %(a,b))

The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation

还有 python documentation 说:

because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

所以你可以使用 str.format:

print("text text {:2d} text text {:2d}".format(a,b))