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.
Post a Comment