Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I alter my code to reverse certain substrings?

I am trying to move the first 2 characters in a string to the end, and the last 2 characters to the front. I then want to reverse the characters that I have moved.

For example, bajui. First we swap the first and last two characters, giving uijba, and then I want to reverse ui into iu and ba into ab, and thus the final result should be iujab.

Here is my current code:

def startToEnd(kata):
   kata = kata[-2:] + kata[2:3] + kata[:2]
   return kata
print(startToEnd("bajui"))

with this it will give uijba. How can I reverse the characters that have been moved?

like image 868
Walls Avatar asked May 17 '26 00:05

Walls


1 Answers

You can just use string slicing to achieve this - Note this will only work as intended for strings of at least length 4.

Code:

def startToEnd(kata):
    return kata[:-3:-1] + kata[2:-2] + kata[1::-1]

Output:

>>> startToEnd('makam')
'makam'
>>> startToEnd("bajui")
'iujab'
like image 170
CDJB Avatar answered May 18 '26 13:05

CDJB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!