Search code examples
pythonpython-3.xstringswap

How to Swap Chars like a byte-swap but with in a String with Python?


I'm looking for the fastest way (computationally speaking) to do :

CDAB to ABCD

Say I have this list of strings:

a = ['3412','7895','0042','1122','0001']

And I want my output to be a string b = 12349578420022110100 with something like a 16-bit byte-swap

My code goes (I used the entry as a string but it will be a list soon):

a = '34127895004211220001'
b = ''
i = 0

while (i < len(a)):
    b = b + a[i + 2:i + 4] + a[i:i + 2]
    i = i + 4

print(b)

b = 12349578420022110100

Do you think this approach is the best one ?


Solution

  • Like @Ashwini mentioned it's depend on input size. But my approach is to add how many possible functions so my solution is this:

    def swap(string):
        return string[-2:] + string[:-2]
    
    a = ['3412','7895','0042','1122','0001']
    s = ''.join(swap(a[i]) for i in range(len(a)))
    
    print(s)