0

I have this following code:

from itertools import permutations
a = list(itertools.permutations(['test', 'text', 'new']))

This produces:

[('test', 'text', 'new'),
 ('test', 'new', 'text'),
 ('text', 'test', 'new'),
 ('text', 'new', 'test'),
 ('new', 'test', 'text'),
 ('new', 'text', 'test')]

How can do it so that for every row the string is joined and the space between the words are replaced with &. Thus for example the first line in this above list would look like :

test & text & new
AMC
  • 2,642
  • 7
  • 13
  • 35
Slartibartfast
  • 1,058
  • 4
  • 26
  • 60

2 Answers2

2
strings = [" & ".join(x) for x in a]

Output:

>>> for s in strings: print(s)

test & text & new
test & new & text
text & test & new
text & new & test
new & test & text
new & text & test
>>> 
MohitC
  • 4,541
  • 2
  • 34
  • 55
  • What do you mean by why you are not able to do that? Do you face any error? and did you put "the list" as string inside join function? Join function will always take a list as input – MohitC Apr 26 '20 at 00:51
  • Here is what i did, `s = "&"' `and `s.join(a)` and i get `' TypeError: sequence item 0: expected str instance, tuple found'` ! – Slartibartfast Apr 26 '20 at 00:56
  • 1
    @newcoder use `[" & " .join(x[0]) for x in a]` – sahasrara62 Apr 26 '20 at 01:01
2

Late answer, but for py >= 3.6 you can also use:

from itertools import permutations

a = [f"{x[0]} & {x[1]} & {x[2]}" for x in permutations(['test', 'text', 'new'])]

Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268