1

In python, how would you swap the first and last parts of a string but leave the middle character in the same place? For example, if I have ABCDE, then the result would be DECAB.

def swap(str1):
    return str1[-1]+str1[1:-1]+str1[:1]
print(swap("Hello"))

With this, I am only able to swap the first and last letter of the string. So the result for 'Hello' is 'oellH'.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Tutis
  • 11
  • 1
  • you just want to print it in this way or want to modify string? – Lalit Verma Aug 30 '19 at 05:16
  • This question is not a duplicate of the classical 'Reverse a string in Python': the OP wants to swap the substrings before and after the middle of the string, keeping the chars in order in each block, not reverse the whole string. – Thierry Lathuille Aug 30 '19 at 05:27

1 Answers1

-1

You can obtain the index of the middle character with the floor division //:

5 //2 
# 2

So, you can change your code like this:

def swap(str1):
    middle = len(str1) // 2
    return str1[middle+1:] + str1[middle] + str1[:middle]

print(swap("ABCDE"))
# DECAB

Note that this only works for strings with an odd number of characters. We could modify the function to also handle strings with even numbers of chars, just swapping both halves in this case:

def swap(str1):
    middle = len(str1) // 2

    if len(str1) % 2 == 0:
        # even length
        return str1[middle:] + str1[:middle]
    else:
        # odd length
        return str1[middle+1:] + str1[middle] + str1[:middle]

print(swap("ABCDE"))
# DECAB

print(swap("ABCDEF"))
# DEFABC
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50