Search code examples
pythonpython-itertoolsmore-itertools

How to remove string quotations, commas and parenthesis from Python itertools output?


This nice script generates all 4 character permutations of the given set s, and prints them on new lines.

import itertools


s = ('7', '8', '-')

l = itertools.product(s, repeat=4)

print(*l, sep='\n')

Sample output:

...
('9', '-', '7', '8')
('9', '-', '7', '9')
('9', '-', '8', '7')
('9', '-', '8', '8')
('9', '-', '8', '9')
...

I can't figure out how to remove all single quotes, commas and left/right parenthesis.

Desired output:

...
9-78
9-79
9-87
9-88
9-89
...

Tried adding:


c = []

for i in l:
    i = i.replace(",", '')
    c.append(i)

print(*c, sep='\n')

Error: AttributeError: 'tuple' object has no attribute 'replace'

Also tried: I can't seem to find where to put the print(' '.join()) logic.


Solution

  • Each time you are printing a value, you can use:

    for vals in l:
        print("".join([str(v) for v in vals]))
    

    This just joins all the characters, noting that .join requires the values to be strings.

    You can also use:

    for vals in l:
        print(*vals)
    

    ... but that has a space between values.