首页 > 解决方案 > 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.

标签: pythonstringfunction

解决方案


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]

推荐阅读