mewingpants
mewingpants

Reputation: 3

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.

Upvotes: 0

Views: 179

Answers (2)

learning2learn
learning2learn

Reputation: 411

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()])

Upvotes: 3

Woodford
Woodford

Reputation: 4449

swap_seq shouldn't be a string. It's a sequence of index values so use a more appropriate data type, list a list of integers:

swap_seq=[1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16]
swapped=''.join([s[i] for i in swap_seq])

Upvotes: 0

Related Questions