编写一个函数 swap_halves(s),该函数接受字符串 s,并返回一个新字符串,其中字符串的两半已交换



编写一个函数swap_halves(s),该函数s接受字符串,并返回一个新字符串,其中两个 字符串的一半已被交换。 例如,swap_halves("good day sunshine")将返回'sunshine good day'。 我尝试了类似的东西

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):]  )

不知道如何在不使用if或其他语句的情况下做到这一点。

我不知道你到底想要什么,但这可能会起作用

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 ")
def func(s):
return(s[0:1]*3+s[1:]+s[-1:]*3)

你会想要.split()文本,除非你不介意一些单词被删减,比如说如果你的中间索引落在一个单词中,正如有人指出的那样,对于字符串good day bad sunshine你不会想要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

根据要求:

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

最新更新