如何在Python中连接字符串和整数?

2024-10-03 19:22:45 发布

您现在位置: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

我得到一个错误:

^{pr2}$

我的问题是:有没有关于如何将“item_bicycleadcategory”传递给exec表达式的线索?在

谨致问候


Tags: integers代码informodelobjectscountwith
3条回答

对于python 2.7,可以使用以下格式:

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

输出:

Please give me 3 beer

您可以使用format执行许多操作,例如:

^{pr2}$

输出:

Please give me 3 Please beer.

您已经在使用python的格式语法:

"string: %s\ndecimal: %d\nfloat: %f" % ("hello", 123, 23.45)

更多信息:http://docs.python.org/2/library/string.html#format-string-syntax

首先,exec甚至比eval()更危险,所以请绝对确保您的输入来自可信来源。即使那样,你也不应该这么做。看起来你在使用一个web框架或者类似的东西,所以不要这么做!在

问题是:

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

仔细看看。您正试图将字符串格式参数放在没有格式字符串的单父项中,并且没有')' % count_bicycleadcategory。在

你可以这样做:

^{pr2}$

但您真正应该做的是根本不要使用exec!在

创建一个模型实例的列表并使用它。在

相关问题 更多 >