[Tutor] Using 'join ' function to create a string

bob gailer bgailer at alum.rpi.edu
Fri Dec 21 17:56:16 CET 2007


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

Best way? Depends on what you mean by "best".

My solution:

Z = ', '.join(i+':'+str(j) for i, j in zip(X,Y))

It's interesting to note how close your output is to a dictionary display:

dict(zip(X,Y)) -> {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

BTW is is customary in Python to start variable names with lower case 
letters (x,y,z) in this case.
Title case  is then used for Classes
CAPS is used for CONSTANTS


More information about the Tutor mailing list