My question is a slight variation of How do I pass a variable by reference? - however I still can't find a simple solution to the problem illustrated below: how can I alter the values of the outer string variables from within a for-loop?
str1 = 'before'
str2 = 'before'
for i in str1,str2:
print "%s" % (i)
i = "after"
for i in str1,str2:
print "%s" % (i)
Thanks for the helpful responses below however they haven't really helped with my specific problem, the code below is less generic but better reflects my use case:
import feedparser
d = feedparser.parse('http://feeds.feedburner.com/FrontlineAudiocastPbs?format=xml')
name = d.feed.title[:127]
description = d.feed.subtitle[:255]
strs = [name,description]
for i, s in enumerate(strs):
try:
strs[i] = unicode(strs[i])
except:
strs[i] = "Invalid unicode detected!"
for s in name,description:
print s
You can see that the two original string variables are not being updated. The for-loop is intended to detect and handle malformed string such as the assignment to 'description'.. so any 'associated' advice would be appreciated.
I like the elegance of the list comprehension slice assignment approach below and would ideally use that technique.