简体   繁体   中英

Python - How to concatenate Strings and Integers in Python?

I'm with some trouble getting this code to work:

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

I'm getting an error:

Type Error, not all arguments converted during string formatting

My question is: Any clue on how I pass the "item_bicycleadcategory" to the exec expression?

Best Regards,

You are already using python's format syntax:

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

More info here: http://docs.python.org/2/library/string.html#format-string-syntax

First, exec is even more dangerous than eval() , so be absolutely sure that your input is coming from a trusted source. Even then, you shouldn't do it. It looks like you're using a web framework or something of the sort, so really don't do it!

The problem is this:

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

Take a closer look. You're trying to put the string formatting argument to a single parentesis with no format strings with ')' % count_bicycleadcategory .

You could do this:

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

But what you really should be doing is not using exec at all !

Create a list of your model instances and use that instead.

for python 2.7 you could use format:

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

out:

Please give me 3 beer

you could do many things with format , for example:

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

out:

Please give me 3 Please beer.

try this :

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

(you mustn't mix %s and string + concatenation at the same time)

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM