[Tutor] Using 'join ' function to create a string
dkuhlman at rexx.com
Fri Dec 21 17:51:47 CET 2007
On Fri, Dec 21, 2007 at 09:33:31AM -0700, Eric Brunson wrote:
> lechtlr wrote:
> > Hi there,
> > I would like to know what is the best way to create a string object
> > from two different lists using 'join' function. For example, I have X
> > = ['a', 'b', 'c', 'd', 'e'] and Y = [1, 2, 3, 4, 5]. From X and Y, I
> > want to create a string Z = 'a:1, b:2, c:3, d:4, e:5'.
> How about something like this:
> ", ".join( '%s:%s' % ( x, y ) for x, y in zip( X, Y ) )
Slick. I believe that the argument you are passing to join() is
the result of a generator expression. Am I right?
And, I did not know that str.join(seq) could take an iterator as
opposed to a plain sequence. Thanks for showing us that.
Back to the original poster's problem, you could also try map() and
', '.join(map(lambda x,y: '%s:%s' % (x, y, ), X, Y))
Or, maybe unrolling it makes it more readable:
In : fn = lambda x,y: '%s:%s' % (x, y, )
In : ', '.join(map(fn, a, b))
Out: 'aa:11, bb:22, cc:33'
More information about the Tutor