zdm
zdm

Reputation: 531

How to print a list of pairs without commas between pairs in python?

I have two lists of the same size

a = [1, 2, 3, 4, 5]

and

b = [2, 3, 4, 5, 6]

I would like to print the zipped list zip(a, b) but without commas between pairs as follows:

c = [(1, 2) (2, 3) (3, 4) (4, 5) (5, 6)]

When I do

print(str(list(zip(a, b))).replace(',', ''))

I get

[(1 2) (2 3) (3 4) (4 5) (5 6)]

which removes all commas even the ones inside each pair, (1 2).

I want the output to be like

[(x, y) (z, t) (u, v) ...]

Upvotes: 1

Views: 901

Answers (3)

kederrac
kederrac

Reputation: 17322

you can use f-string with str join

f"[{', '.join([str(e).replace(',','') for e in c])}]"

or you can use regular expression:

import re 

re.sub('\([^()]*\)', lambda x: x.group().replace(",", ""), str(c))

output:

[(1 2), (2 3), (3 4), (4 5), (5 6)]

Upvotes: 1

Olvin Roght
Olvin Roght

Reputation: 7812

print("[" + " ".join(map(str, zip(a, b))) + "]")

or

print("[", " ".join(map(str, zip(a, b))), "]", sep="")

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49803

You can use a more specific argument for replace:

print(str(list(zip(a, b))).replace('), (', ') ('))

Upvotes: 1

Related Questions