写一个函数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