Monday, December 6, 2010

string substitution in list

While coding the other day ... I came across this suspiciously looking code that almost look like it would work ...

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:

Anonymous said...

It's "list comprehension", which is even more fun to say. I don't think I've ever seen "list substitution" used anywhere.

lowks said...

Marius: I guess I can call it ... string substitution via list comprehension.

alex dante said...

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...)

lowks said...

Alex: Bravo!

Frank said...

['My name is %s' % name for name in ['Earl', 'Matthew', 'David']]

More concise I think.