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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With