Reputation: 1289
I'm attempting to create a python script that chooses the next item from a list in a dict on each iteration and replaces the key in the text with the current item. The issue, however, is that it won't return the list item that matches an integer that is set by a variable.
The code:
for x in range(0,runs):
for k,v in shortcodes.iteritems():
description = description.replace('{'+k+'}', v[x])
print description
Simply continues to replace the key value in the text with the first list item, rather than incrementing. If I manually remove x
and set it to a higher integer, it responds correctly. Similarly, for sanity sake, printing x
as it goes along confirms that x
is increasing.
So, why is it ignoring x
and staying with 0
?
Upvotes: 0
Views: 71
Reputation: 2472
The thing is in your code the for loop only replaces the keyword the first iteration. all the other iterations there are no keywords left to replace, since you have replaced them all with the first element of your valueitem.
I think a more promising solution is something like this
for k,v in shortcodes.iteritems():
for x in v:
index = description.find('{'+k+'}')
description[index:index+len('{'+k+'}')] = description[index:index+len('{'+k+'}')].replace('{'+k+'}', x)
print description
now you itereate over your valuelist for each key instead of the other way around,
and since you want to change every keyword with anoter value, you only replace the substrings you want to change. with find()
you get the postion of the lowest index of the substring in the actual string. and with len()
you get the legth of the parametervalue
Upvotes: 1