substituted = ["My name is %s","My name is %s", "My name is %s" ] % ["Earl","Matthew","David"]
So used to looking at string substitution, I almost thought that code could work ... of course in order for that to work correctly ... it would have to be something like this ...
strings = ["My name is %s","My name is %s", "My name is %s" ] names = ["Earl","Matthew","David"] substituted = [ string % name for string,name in zip(strings,names) ]
It's string substitution and list substitution .. Repeat that 10 times :). It's always good and enlightening to strip right down to the basics most days. Go on run the first part of the code and see what you get.
5 comments:
It's "list comprehension", which is even more fun to say. I don't think I've ever seen "list substitution" used anywhere.
Marius: I guess I can call it ... string substitution via list comprehension.
class TemplateList(list):
def __mod__(self, other):
return [s % v for (s, v) in zip(self, other)]
>>> substituted = TemplateList(['My name is %s'] * 3) % ['Earl', 'Matthew', 'David']
>>> print substituted
['My name is Earl', 'My name is Matthew', 'My name is David']
:)
(Sorry, the lack of pre tags makes that look godawful...)
Alex: Bravo!
['My name is %s' % name for name in ['Earl', 'Matthew', 'David']]
More concise I think.
Post a Comment