Python 2.7 我试图在Python2.7中创建一个反向函数

Python 2.7 我试图在Python2.7中创建一个反向函数,python-2.7,function,loops,Python 2.7,Function,Loops,我得到的是“none”作为我的输出,而不是相反的字符串。我不确定我是否打印错了东西。我对循环比较陌生,所以请容忍我,但基本目标是反转“旧字符串” old_string=("I am testing") #Defining old_string def reverse(old_string): rng=range((len(old_string))-1,11,1) #rng= the range of the number of index values in old_stri

我得到的是“none”作为我的输出,而不是相反的字符串。我不确定我是否打印错了东西。我对循环比较陌生,所以请容忍我,但基本目标是反转“旧字符串”

 old_string=("I am testing") #Defining old_string


 def reverse(old_string):

     rng=range((len(old_string))-1,11,1) #rng= the range of the number of index values in old_string, starting with max-1 ending at 0 by steps of -1
     new_string='' #New string equals the following loop

     for index in rng: #For index in the above range


         new_string=new_string,old_string[index] #New string equals itself PLUS the origninal old string using index values of 'index'
         return new_string


 print reverse(old_string)

以下是您的版本中的错误:

def reverse(old_string):
    rng=range((len(old_string))-1,-1,-1) # this is the correct range that you want
    new_string='' 

    for index in rng:
        new_string += old_string[index] # concatenate strings with + (or +=)

    return new_string   # return outside of your loop
顺便说一句,您总是可以使用

s[::-1]

以下是您的版本中的错误:

def reverse(old_string):
    rng=range((len(old_string))-1,-1,-1) # this is the correct range that you want
    new_string='' 

    for index in rng:
        new_string += old_string[index] # concatenate strings with + (or +=)

    return new_string   # return outside of your loop
顺便说一句,您总是可以使用

s[::-1]

通过在for循环中放置return语句,可以在for循环完成之前退出函数。您需要将return语句置于for循环之外

另外,如果只想反转字符串,可以执行以下操作

“你好,世界”[:-1]
“dlrow olleh”

通过将return语句放置在for循环中,可以在for循环完成之前退出函数。您需要将return语句置于for循环之外

另外,如果只想反转字符串,可以执行以下操作

“你好,世界”[:-1]
“dlrow olleh”我的return语句在for循环中,因此结束了循环。所以,我把它移出了循环,所以现在当循环完全完成时,它就完成了。(我还固定了范围编号)

我的return语句在for循环中,因此结束了循环。所以,我把它移出了循环,所以现在当循环完全完成时,它就完成了。(我还固定了范围数)

返回语句是否真的在
for
循环中?这似乎是一个错误。另外,为什么您要使用
新字符串
旧字符串[索引]
连接起来?这将创建一个元组。您可能想改用
+
。您的范围注释和范围值不匹配。这是三个问题。您的范围必须是range(len(old_string)-1,-1,-1),您需要有new_string+=old_string[index],并在for循环之外返回(仅缩进1级)。这些更改将修复您的代码。对于python,如果您陷入困境,我建议您在控制台上一步一步地运行它们,然后您就可以看到您想要的是不是真的发生了。最简单的调试方法,尤其是当您刚开始时。@EmadY:rng实际上应该是
范围(len(旧字符串)-1),-1,-1)
,所以
0
th字符可以附加在
return
语句后面,真正在
for
循环中?这似乎是一个错误。另外,为什么您要使用
新字符串
旧字符串[索引]
连接起来?这将创建一个元组。您可能想改用
+
。您的范围注释和范围值不匹配。这是三个问题。您的范围必须是range(len(old_string)-1,-1,-1),您需要有new_string+=old_string[index],并在for循环之外返回(仅缩进1级)。这些更改将修复您的代码。对于python,如果您陷入困境,我建议您在控制台上一步一步地运行它们,然后您就可以看到您想要的是不是真的发生了。最简单的调试方法,尤其是当您刚开始时。@EmadY:rng实际上应该是
范围(len(旧字符串)-1),-1,-1)
,因此可以附加
0
第个字符