Daniel Arges
Daniel Arges

Reputation: 365

inverting strings (mirroring from center)

Isn't there a simpler way to invert a string like EURUSD to USDEUR, instead of using this code:

new_str = old_str[-3:] + old_str[:3]

Upvotes: 0

Views: 67

Answers (1)

John Coleman
John Coleman

Reputation: 52008

There is nothing shorter than what you are doing. I suspect that you were thinking of the trick for reversing a string, where s[::-1] reverses it. Here you are reversing by chunks of length 3. No one slice operation can do that.

If you do this sort of thing often, including for longer strings, writing a function might help:

def reverse_chunks(s,k):
    """reverses the order of k-sized chunks in s"""
    return ''.join([s[i:i+k] for i in range(0,len(s),k)][::-1])

Then, for example:

>>> reverse_chunks('EURUSD',3)
'USDEUR'

Based on this, you could of course write a more specialized:

def invert(s):
    return reverse_chunks(s,len(s)//2)

Upvotes: 1

Related Questions