2013-03-14 89 views
1

我想這一點,其中i是一個整數:包括在打印語句中的整

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

和它說:「不能連接STR和INT」。我曾嘗試各種組合:

int(i) + 1 
i + int(1) 

...但它不工作

回答

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

心靈括號。

(該%運算符與比+運營商更緊密,所以你拉閘努力加1格式的字符串,這是一個錯誤。)

2

如何:

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

的Python ('...'%i)+ 1

1

str.format如果您的Python版本足夠新以支持它(Python2.6 +)†看到您甚至不需要擔心這裏的%+的優先級。

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

或作爲問題標題所暗示 - 使用print語句

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

在Python3,print是一個函數,所以你需要調用它

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

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