kaycaborr
kaycaborr

Reputation: 49

Python write zip into text file

How can I write zip into a text file?

x=[a,b,c,d,e]
y=[1,2,3,4,5]

zipped = zip(x,y)

output = open("out.txt","w")
output.write(zipped)
output.close()

I would like to get a1,b2,c3,d4,e5 but write() argument must be str not zip.

Upvotes: 3

Views: 1429

Answers (3)

Paul Panzer
Paul Panzer

Reputation: 53099

If you have a modern Python version you can use f-string

>>> ','.join(f'{i}{j}' for i, j in zip('abcde', range(1,6)))
'a1,b2,c3,d4,e5'

On older versions format can be used

>>> ','.join('{}{}'.format(*p) for p in zip('abcde', range(1,6)))
'a1,b2,c3,d4,e5'

Upvotes: 0

akkerman
akkerman

Reputation: 119

This will give you the desired output:
result = ','.join([ a+str(b) for (a,b) in zipped ])
it concatenates the letter and the number into a string and then joins the strings separating them with a comma


If you only wanted to create a string from the zip:
result = ''.join(map(str, zipped))
which creates a string of each zipped element and then joins them together


Upvotes: 1

Argus Malware
Argus Malware

Reputation: 787

you can write this way

x=['a','b','c','d','e']
y=[1,2,3,4,5]
zipped = zip(x,y)
with open('out.txt', 'w') as fp:
     fp.write(''.join('%s%s' % x for x in zipped))

Upvotes: 1

Related Questions