Skip to content Skip to sidebar Skip to footer

Write A Function Swap_halves(s) That Takes A String S, And Returns A New String In Which The Two Halves Of The String Have Been Swapped

Write a function swap_halves(s) that takes a string s, and returns a new string in which the two halves of the string have been swapped. For example, swap_halves('good day sunshine

Solution 1:

I don't know what exactly you want but this might work

defswap_halves (s):
  '''Returns a new string in which the two halves of the spring have swapped'''
  i = int(len(s)/2)
  print(s[i:] + s[:i]  )
swap_halves("good day sunshine ")

Solution 2:

def func(s):
    return(s[0:1]*3+s[1:]+s[-1:]*3)

Solution 3:

You are going to want to .split() the text unless you don't mind some words getting cut say if your middle index falls in a word as someone pointed out, for string good day bad sunshine you wouldn't want ad sunshinegood day b

def swapper(some_string):
    words = some_string.split()
    mid = int(len(words)/2)
    new = words[mid:] + words[:mid]
    return' '.join(new)

print(swapper('good day bad sunshine'))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 images.py
bad sunshine good day

As requested :

def tripler(text):
    new = text[:1] * 3 + text[1:-1] + text[-1:] * 3returnnew

print(tripler('cayenne'))
(xenial)vash@localhost:~/python/stack_overflow$ python3.7 images.py
cccayenneee

Post a Comment for "Write A Function Swap_halves(s) That Takes A String S, And Returns A New String In Which The Two Halves Of The String Have Been Swapped"