2024-10-06 11:19:47 发布
网友
我正在尝试,其中i是一个整数:
i
sys.stdout.write('\thello world %d.\n' % i+1)
它说“不能连接str和int”。我试过各种组合:
。。。但没用
如果您的Python版本足够新以支持它(Python2.6+)†最好使用str.format,这里甚至不需要担心%和{}的优先级。在
str.format
%
sys.stdout.write('\thello world {}.\n'.format(i+1))
或者正如问题的标题所暗示的那样-使用打印声明
在Python3中,print是一个函数,所以您需要这样调用它
print
print('\thello world {}.'.format(i+1))
†在Python2.6中,您需要使用{0},而不是普通的{}
{0}
{}
sys.stdout.write('\thello world %d.\n' % (i+1))
小心括号。在
(%运算符比+运算符绑定得更紧密,因此您最终尝试向格式化字符串添加1,这是一个错误。)
+
关于:
Python将您的方式解释为('…'%i)+1
如果您的Python版本足够新以支持它(Python2.6+)†最好使用}的优先级。在
str.format
,这里甚至不需要担心%
和{或者正如问题的标题所暗示的那样-使用打印声明
^{pr2}$在Python3中,
print
是一个函数,所以您需要这样调用它†在Python2.6中,您需要使用
{0}
,而不是普通的{}
小心括号。在
(
%
运算符比+
运算符绑定得更紧密,因此您最终尝试向格式化字符串添加1,这是一个错误。)关于:
Python将您的方式解释为('…'%i)+1
相关问题 更多 >
编程相关推荐