Search code examples
pythonstringlistswapmodulo

swap group of characters every words in list


I have a list like :

s=['eb736d0020000000073a...002300001f', '00bd860020000020efad...002300003f', '1452770020000040ef53...002300005f', 'fbeadb002000006006ac...002300007f', 'ec38b600200000801441...002300009f', '07251600200000a004a2...00230000bf', '12866c00200000c0ee2c...00230000df', 'f5cf2600200000e0f10d...00220000ff', '0a331500230000ffeefe...002200011f', '0e0ddc002300011f0cd0...002200013f', 'edd254002300013f0edc...002200015f', 'fbe547002300015ff0b7...002200017f', '14506f002300017ff37c...002200019f', 'f8a2a0002300019f112f...00220001bf', ...]

the size of one element is variable, but modulo 16 characters. For each element of the list, I want to : swap the first 8 characters with the second 8 characters, every 16 characters :

s[0] = 'aaaaaaaabbbbbbbb'
s = s[0][8:16] + s[0][0:16]
s[0] = 'bbbbbbbbaaaaaaaa'

so ok for one element, but how reproduce that for one element every 16 characters for each element of the list without for loop ? :

s[0] = 'aaaaaaaabbbbbbbbccccccccdddddddd' <= 2048 characters
s[1] = 'eeeeeeeeffffffffgggggggghhhhhhhh' <= 2048 characters
to
s[0] = 'bbbbbbbbaaaaaaaaddddddddcccccccc'
s[1] = 'ffffffffeeeeeeeehhhhhhhhgggggggg'

I use for loop and I see it's slow for big datas. I want to not use a loop but something more efficient


Solution

  • Loop will be always needed, but you can try to use list comprehension + str.join to speed-up things:

    lst = ["aaaaaaaabbbbbbbbccccccccdddddddd", "eeeeeeeeffffffffgggggggghhhhhhhh"]
    
    out = [
        "".join(f"{(part:=s[i : i + 16])[8:16]}{part[0:8]}" for i in range(0, len(s), 16))
        for s in lst
    ]
    print(out)
    

    Prints:

    [
      'bbbbbbbbaaaaaaaaddddddddcccccccc', 
      'ffffffffeeeeeeeehhhhhhhhgggggggg'
    ]