Rearrange two characters in a string and save the generated strings in a list in Python

I want to swap every two characters in a string and save the output in a list (to check each line later if it exists in the dictionary)

I have seen several codes that change all characters at once, but this is not what I am looking for.

For instance:

var = 'abcde'

Expected Result:

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

How can I do this in Python?

+4
source share
4 answers

To achieve this, you can use the understanding expression below the list:

>>> 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']
+4
source

, 'abced', , (, ):

In [5]: x
Out[5]: 'abcde'

In [6]: [x[:i] + x[i+1] + x[i] + x[i+2:] for i in range(len(x)-1)]
Out[6]: ['bacde', 'acbde', 'abdce', 'abced']
+2

The generator function will not use too much memory for longer strings:

def swap_pairs(s):
    for i in range(len(s) - 1):
        yield s[:i] + s[i + 1] + s[i] + s[i + 2:]

>>> swap_pairs('abcde')
<generator object swap_pairs at 0x1034d0f68>
>>> list(swap_pairs('abcde'))
['bacde', 'acbde', 'abdce', 'abced']
+2
source

Here is the approach re:

x = 'abcde'
[re.sub(f'(.)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))]
# ['bacde', 'acbde', 'abdce', 'abced']

And an option that skips double characters:

x = 'abbde'
[s for s, i in (re.subn(f'(.)(?!\\1)(.)(?=.{{{i}}}$)', "\\2\\1", x) for i in reversed(range(len(x)-1))) if i]
# ['babde', 'abdbe', 'abbed']
+1
source

Source: https://habr.com/ru/post/1691507/


All Articles