首页 > 解决方案 > 编写一个函数 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):]  )

不知道如何在没有 usingif或其他语句的情况下执行此操作。

标签: pythonswap

解决方案


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

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

推荐阅读