用于交换字符串中第一个和最后一个字母的 Python 代码 [英] Python code to swap first and last letters in string

查看:56
本文介绍了用于交换字符串中第一个和最后一个字母的 Python 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串,返回一个新字符串,其中第一个和最后一个字符已经交换.

Given a string, return a new string where the first and last chars have been exchanged.

front_back('code') → 'eodc'
front_back('a') → 'a'
front_back('ab') → 'ba'

以上是我试图解决的 www.codingBat.com 上提供的问题之一,下面是我为此编写的代码.

The above is one of the problems provided on www.codingBat.com I was attempting to solve and below is the code I wrote to do so.

def front_back(str):     
    str = list(str)
    first = [str[0]]
    last = [str[-1]]
    middle = str[1:-1]
    print ''.join (last + middle + first)

现在,当我在计算机上的 python 2.7 中运行此代码时,此代码似乎可以正常工作,但是在代码 bat 上运行时,出现以下错误:错误:列表索引超出范围"

Now this code seems to work properly when I run it in python 2.7 on my computer but when running it on code bat I get the following error: "Error:list index out of range"

现在我想我很清楚这个错误意味着什么,但我不明白为什么我会得到它,因为我引用的任何索引基本上都保证在至少 2 个字符的字符串中.

Now I think I have a pretty good idea of what this error means, but I don't understand why I am getting it due to the fact any indexes I am referencing are basically guaranteed to be in string of at least 2 characters.

推荐答案

对于空字符串 ('') 作为 str[,您可能得到了 IndexError0] 在这种情况下将超出范围.如所写,您的代码也会为 1 个字符的字符串生成无效结果.要修复它,您可以 return 原始字符串,如果其长度为 <2. 此外,使用字符串切片会更简单(更快):

You probably got an IndexError for an empty string ('') as str[0] would be out of range in that case. As written, your code would also produce an invalid result for a 1-character string. To fix it, you can return the original string if its length is < 2. Also, it would be much simpler (and faster) to use string slicing:

def front_back(string):
    if len(string) < 2:
        return string
    return string[-1] + string[1:-1] + string[0]

(作为旁注,不要使用 str 作为变量名,因为它会影响 内置 str 函数).

(As a side note, don't use str for a variable name as it'll shadow the built-in str function).

这篇关于用于交换字符串中第一个和最后一个字母的 Python 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆