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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With