在 Python 中使用 sys.stdout.write 嵌入变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4669791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Embed variable using sys.stdout.write in Python
提问by abel
I can embed variables using the print statement in python in this way
我可以通过这种方式在python中使用print语句嵌入变量
i=10
print "Value is %s" % (i)
Output
输出
Value is 10
Value is 10
but doing this
但这样做
i=10
sys.stdout.write ("Value is %s") % (i)
gives me the following error
给我以下错误
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
Can I embed variables using sys.stdout.write instead of print?
我可以使用 sys.stdout.write 而不是打印来嵌入变量吗?
采纳答案by Sven Marnach
You got the parentheses wrong. Should be
你把括号弄错了。应该
i=10
sys.stdout.write("Value is %s" % i)
The %operator takes a string and a tuple (or a single object) as arguments. You tried to apply the operator to the return value of sys.stdout.write(), which is None. You need to apply it to the string before it is passed to sys.stdout.write().
在%操作者需要一个字符串和元组(或单个对象)作为参数。您尝试将运算符应用于 的返回值sys.stdout.write(),即 None。您需要将其应用于字符串,然后再将其传递给sys.stdout.write().

