在打印语句中包含整数

2024-10-06 11:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试,其中i是一个整数:

sys.stdout.write('\thello world %d.\n' % i+1)

它说“不能连接str和int”。我试过各种组合:

^{pr2}$

。。。但没用


Tags: worldstdoutsys整数writeintstrpr2
3条回答

如果您的Python版本足够新以支持它(Python2.6+)最好使用str.format,这里甚至不需要担心%和{}的优先级。在

sys.stdout.write('\thello world {}.\n'.format(i+1))

或者正如问题的标题所暗示的那样-使用打印声明

^{pr2}$

在Python3中,print是一个函数,所以您需要这样调用它

print('\thello world {}.'.format(i+1))

†在Python2.6中,您需要使用{0},而不是普通的{}

sys.stdout.write('\thello world %d.\n' % (i+1))

小心括号。在

%运算符比+运算符绑定得更紧密,因此您最终尝试向格式化字符串添加1,这是一个错误。)

关于:

sys.stdout.write('\thello world %d.\n' % (i+1))

Python将您的方式解释为('…'%i)+1

相关问题 更多 >