Home > Mobile >  Print every possible 2-letter combination from a string containing 3 letters in python
Print every possible 2-letter combination from a string containing 3 letters in python

Time:04-18

The below code currently produces only 3 letter combinations from the 3-letter string. How can I revise the code to produce every 2-letter combination and add "2022" to every combination (such as CE2022, CO2022, OC2022, EO2022, etc.)?

d='CEO'
t=list(itertools.permutations(d,len(d)))
for i in range(0,len(t)):
    print(''.join(t[i]))

Output:
CEO
COE
ECO
EOC
OCE
OEC

CodePudding user response:

Same as the other answer but using a list comprehension:

import itertools

d = 'CEO'

result = ["".join(i)   "2022" for i in itertools.permutations(d, 2)]

print(result)

CodePudding user response:

If you change len(d) to 2 you get every 2-letter combination:

d='CEO'
t=list(itertools.permutations(d,2))
for i in range(0,len(t)):
    print(''.join(t[i]) '2022')

Output:

CE2022
CO2022
EC2022
EO2022
OC2022
OE2022

You can also make this more Pythonic:

import itertools
d='CEO'
t=itertools.permutations(d,2)
for i in t:
    print(''.join(i) '2022')
  • Related