Search code examples
pythondoubleswapdigits

Python swapping sequence double digits


Example of the code that works great

s="abc123"
swap_seq="103254"
swapped=''.join([s[int(i)] for i in swap_seq])
if s[0].isupper(): swapped.capitalize()
print (swapped)

but I have a large amount of characters that I need to be swapped 18 exactly, just wondering how to do the double digits

The example i'm trying to get it working with is the following.

s="0123456789abcdefgh"
swap_seq="1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16"
swapped=''.join([s[int(i)] for i in swap_seq])
if s[0].isupper(): swapped.capitalize()
print (swapped)

Tried ["0", "1", "2"] but then the input would have to be exactly the same length or I get an error.

What i'm trying to do is have a user input anything up to 18 characters and the code will swap the letters/numbers around.


Solution

  • I think this is what you want, didn't try it. The way I read your code, you are indexing s, using the sequence outlined in swap_seq, so the split will give you a list of the positions, and i, instead of being each possible character in swap_seq, which includes spaces, will now be a list of the strings with the spaces taken out.

    swapped=''.join([s[int(i)] for i in swap_seq.split()])