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

雨燕双飞 提交于 2019-12-14 03:32:50

问题


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") would return 'sunshine good day'. I tried something like

def swap_halves (s):
    '''Returns a new string in which the two halves of the spring have swapped'''

    return (s[0:len(s)] + s[len(s):]  )

not sure how to do it without using if or other statements.


回答1:


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

def swap_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 ")



回答2:


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



回答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:] * 3
    return new

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


来源:https://stackoverflow.com/questions/52392245/write-a-function-swap-halvess-that-takes-a-string-s-and-returns-a-new-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!