为什么我的 front_back 程序在 Python 中不起作用?
Why doesn't my front_back programme in Python work?
任务是:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
它不会起作用,因为 .replace()
将替换该字符的所有出现,不一定只是第一个和最后一个
下面是一个用第一部分、主体部分和最后部分构造字符串的解决方案
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
字符串文字可以切片和添加:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S。 str
是 python 中的内置函数,因此将其用作变量名是个坏主意。
首先,从不调用变量str
。为什么?因为那是 class for Python 字符串的名称。如果您使用相同的名称,那么您将失去它。我用 txt
.
你的长度测试是合理的,但下限可以增加(单个字符会很傻)。
但是使用str.replace()
是行不通的。为什么?那么它可以在您的测试用例中工作,但这只是因为每个角色都是独一无二的。 str.replace()
替换 每个 指定字符串的出现。因此,如果第一个或最后一个字符在其他地方重复出现,那么它也会发生变化。
您可以使用 切片,其中第一个(最左边)字符是 0(零)。您还可以使用负数从右开始索引,因此 -1 是最后一个(最右边的)字符。字符范围从开始到最后一个字符。所以 [1:-1]
从第二个字符到最后一个字符。
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
我在函数中使用 return
,因为这是处理文本的正常方式,您的问题中也要求这样做。
任务是:
Given a string, return a new string where the first and last chars have been exchanged.
def front_back(str):
if len(str)<=0:
return str
else:
front=str[0]
back=str[-1]
new = str.replace(str[0], back)
print new
new_2=new.replace(new[-1], front)
print new_2
front_back("code")
Why?
它不会起作用,因为 .replace()
将替换该字符的所有出现,不一定只是第一个和最后一个
下面是一个用第一部分、主体部分和最后部分构造字符串的解决方案
text = 'code'
first, body, last = text[0], text[1:-1], text[-1]
result = last + body + first
# 'eodc'
字符串文字可以切片和添加:
>>> s = "hello world"
>>> s[-1] + s[1:-1] + s[0]
'dello worlh'
P.S。 str
是 python 中的内置函数,因此将其用作变量名是个坏主意。
首先,从不调用变量str
。为什么?因为那是 class for Python 字符串的名称。如果您使用相同的名称,那么您将失去它。我用 txt
.
你的长度测试是合理的,但下限可以增加(单个字符会很傻)。
但是使用str.replace()
是行不通的。为什么?那么它可以在您的测试用例中工作,但这只是因为每个角色都是独一无二的。 str.replace()
替换 每个 指定字符串的出现。因此,如果第一个或最后一个字符在其他地方重复出现,那么它也会发生变化。
您可以使用 切片,其中第一个(最左边)字符是 0(零)。您还可以使用负数从右开始索引,因此 -1 是最后一个(最右边的)字符。字符范围从开始到最后一个字符。所以 [1:-1]
从第二个字符到最后一个字符。
def front_back(txt):
if len(txt) <= 1:
return txt
else:
new_txt = txt[-1] + txt[1:-1] + txt[0]
return new_txt
print front_back("code")
我在函数中使用 return
,因为这是处理文本的正常方式,您的问题中也要求这样做。