2013-01-06 42 views
0

我一些麻煩此代碼是工作:Python - 如何連接Python中的字符串和整數?

count_bicycleadcategory = 0 
for item_bicycleadcategory in some_list_with_integers: 
    exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory 
    count_bicycleadcategory = count_bicycleadcategory + 1 

我得到一個錯誤:

Type Error, not all arguments converted during string formatting 

我的問題是:我如何通過「item_bicycleadcategory」以任何線索exec表達式?

最好的問候,

+2

這是錯誤的,錯誤的,錯誤的。你爲什麼認爲你需要動態變量名?你不。你需要一本字典。 –

+0

這僅僅是一種非常不安全和晦澀的寫作方式(或者意味着):'values = {pk:BicycleAdCategoryType.objects.get(pk = pk)for pk in some_list_with_integers}'? –

+0

或者多想一想...... BicycleAdCategoryType.objects.get(pk__in = some_list_with_integers)'? –

回答

-2

試試這個:

exec 'model_bicycleadcategory_%d.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%d)' % (count_bicycleadcategory, item_bicycleadcategory) 
1

爲蟒蛇2.7你可以使用格式:

string = '{0} give me {1} beer' 
string.format('Please', 3) 

出來:

Please give me 3 beer

,你可以做很多事情與format,例如:

string = '{0} give me {1} {0} beer' 

出來:

Please give me 3 Please beer.

-1

試試這個:

exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=%s)' % (count_bicycleadcategory, str(item_bicycleadcategory)) 

(你不能同時混合%s和字符串+連接)

2

首先,exec甚至比eval()更危險,所以要絕對確保您的輸入來自可信來源的到來。即使那樣,你也不應該這樣做。它看起來像你使用的是一個Web框架或類似的東西,所以真的不這樣做!

問題是這樣的:

exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' + str(item_bicycleadcategory) + ')' % count_bicycleadcategory 

細看。您正試圖將字符串格式參數放置到單個格式字符串中,而不使用格式字符串')' % count_bicycleadcategory

你可以這樣做:

exec 'model_bicycleadcategory_%s.bicycleadcategorytype = BicycleAdCategoryType.objects.get(pk=' % count_bicycleadcategory + str(item_bicycleadcategory) + ')' 

但是你真正應該做的是不使用exec在所有

創建您的模型實例列表並使用它。

+0

+1用於實際響應錯誤消息;也爲執行警告。 – poke