Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping two characters in a string and store the generated strings in a list in Python

I want to swap every two characters in a string and store the output in a list (to check every string later wether it exists in the dictionary)

I have seen some codes that swap the characters all at once, but that is not what I'am looking for.

For example:

var = 'abcde'

Expected output:

['bacde','acbde','abdce','abced']

How can I do this in Python?

like image 750
Ran Avatar asked Jan 03 '23 00:01

Ran


1 Answers

You may use a below list comprehension expression to achieve this:

>>> var = 'abcde'

#                         v To reverse the substring
>>> [var[:i]+var[i:i+2][::-1]+var[i+2:] for i in range(len(var)-1)]
['bacde', 'acbde', 'abdce', 'abced']
like image 69
Moinuddin Quadri Avatar answered Jan 05 '23 15:01

Moinuddin Quadri