python - 编写一个函数 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
或其他语句的情况下执行此操作。
解决方案
我不知道你到底想要什么,但这可能有用
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 ")
推荐阅读
- leaflet - 传单:如何缩放以保持固定位置?
- django - Django,get和filter查询集方法的属性
- ajax - 如何同时运行多个ajax请求
- vim - 如何对 EJS 文件使用 vim 自动完成功能
- python - Elastic Beanstalk - 命令“/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt”返回非零退出状态 1
- swiftui - 使用 SwiftUI 显示错误
- typescript - 返回从数组参数中输入的键定义的选择类型的函数
- tensorflow - 如何为图像分类问题选择卷积神经网络中密集层的单元数?
- html - 你好,我的链接失效了。每次我尝试点击它们时,它都会提示一个错误,除了主页(索引)链接
- javascript - 每当新请求到来时,如何更改元素的高度