Home > Mobile >  Swap 2-character block with the next one in a list
Swap 2-character block with the next one in a list

Time:07-22

I am trying to implement an algorithm in Python that swaps a 2-character block with the next 2-character block for every block of 4 characters, for example if I have "2d14 56f2" it will be "142d f256". Can someone help me out please? Here's what I've worked on so far but it doesn't work...

        def swap_bits(data):
            data = list(data)
            for x,y in zip(data[::2], data[1::2]):
                
                
                for i in range(0, len(data)-1, 4):
                    x, y = y, x

            return ''.join(data)

Here's the string I wish to swap: "2d14541501158000000000001e000000190000000000030003000300030000200800e01e7c580000d462866058040908018f1d196d0ed5628660f60801001900fc1e"

So it should be 142d15541501... It takes every 4-character blocks and swaps their content in pairs of characters.

CodePudding user response:

I don't think the OP's source data has a space in it (based on later edits). Therefore:

s = "2d14541501158000000000001e000000190000000000030003000300030000200800e01e7c580000d462866058040908018f1d196d0ed5628660f60801001900fc1e"

def swap(s):
    assert len(s) % 4 == 0
    result = []
    for i in range(0, len(s), 4):
        result.append(s[i 2:i 4])
        result.append(s[i:i 2])
    return ''.join(result)

print(swap(s))

Output:

142d15541501008000000000001e00000019000000000003000300030003200000081ee0587c000062d46086045808098f01191d0e6d62d5608608f6000100191efc

CodePudding user response:

This can be done in one line:

def swap(s):
    return " ".join(s.split()[i][2:]   s.split()[i][:2] for i in range(len(s.split())))

print(swap("2d14 56f2"))

Output:

142d f256

CodePudding user response:

check if you can use this :

string = '2d14 56f2'
str_list = string.split(' ')
empty_list = []

for word in str_list:
    new_word = word[2:]   word[:2]
    empty_list.append(new_word)
    
print(' '.join(empty_list))

CodePudding user response:

Like this?

def swap(s):
    blocks = [s[i:i 4] for i in range(0, len(s), 4)]
    for i in range(len(blocks)):
        blocks[i] = blocks[i][2:]   blocks[i][:2]
    return "".join(blocks)

print(swap("2d1456f2"))

Output:

142df256

with string 2d14541501158000000000001e000000190000000000030003000300030000200800e01e7c580000d462866058040908018f1d196d0ed5628660f60801001900fc1e

print(swap("2d14541501158000000000001e000000190000000000030003000300030000200800e01e7c580000d462866058040908018f1d196d0ed5628660f60801001900fc1e"))

Output:

142d15541501008000000000001e00000019000000000003000300030003200000081ee0587c000062d46086045808098f01191d0e6d62d5608608f6000100191efc
  • Related