在Python中使用sys.stdout.write嵌入变量

abe*_*bel 8 python python-2.x

我可以用这种方式在python中使用print语句嵌入变量

i=10
print "Value is %s" % (i)
Run Code Online (Sandbox Code Playgroud)

产量

Value is 10
Run Code Online (Sandbox Code Playgroud)

但这样做

i=10
sys.stdout.write ("Value is %s") % (i)
Run Code Online (Sandbox Code Playgroud)

给我以下错误

TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Run Code Online (Sandbox Code Playgroud)

我可以使用sys.stdout.write而不是print来嵌入变量吗?

Sve*_*ach 16

你的括号错了.应该

i=10
sys.stdout.write("Value is %s" % i)
Run Code Online (Sandbox Code Playgroud)

%操作者需要一个字符串和元组(或单个对象)作为参数.您试图将运算符应用于返回值sys.stdout.write(),即None.您需要在传递给字符串之前将其应用于字符串sys.stdout.write().