python - CodingBat practice question - Python Strings
问题描述
I tried solving this python problem below on CodingBat:
"Given a string (str), return a new string where the first and last characters have been exchanged".
This was my attempt at solving it...which turned out to be incorrect and returned with the error "String index out of range".
def front_back(str):
return str[-1] + str[1:-1] + str [0]
I would be grateful if someone could point out what I'm missing here and explain.
Thank you.
解决方案
See if the modified function below works for you.
def front_back(str):
if len(str) == 0:
return ''
if len(str) == 1:
return str
return str[-1] + str[1:-1] + str [0]
推荐阅读
- c# - 属性匹配
- azure - 使用 Azure Web 应用程序网关在 2 个网站之间进行重定向
- javascript - 我可以使用一个命令发送多个嵌入吗?不和谐.js
- spring - Spring OAuth 重定向 URL 混淆
- twilio - 如何在 Twilio 中删除排队的消息?
- css - 为什么 Firefox 不显示我的 SVG 图标,怎么办?
- python - Vscode Flask 热重载
- go - 如何访问动态生成的 Go 模板变量的值
- c++ - 范围-v3 没有 iota 的无限范围
- python - Robot Framework Selenium For 循环单击导航链接失败并出现 StaleElementReferenceException