编写一个函数 swap_halves(s),它接受一个字符串 s,并返回一个新的字符串,其中字符串的两半已经交换 [英] 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
本文介绍了编写一个函数 swap_halves(s),它接受一个字符串 s,并返回一个新的字符串,其中字符串的两半已经交换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编写一个函数swap_halves(s)
,它接受一个字符串s
,并返回一个新的字符串,其中两个字符串的一半已被交换.例如,swap_halves("good day sun")
将返回 'sunshine good day'
.我试过类似
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):] )
不知道如何在不使用 if
或其他语句的情况下做到这一点.
not sure how to do it without using if
or other statements.
推荐答案
def func(s):
return(s[0:1]*3+s[1:]+s[-1:]*3)
这篇关于编写一个函数 swap_halves(s),它接受一个字符串 s,并返回一个新的字符串,其中字符串的两半已经交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文