Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么我的递归函数不是串接字符串?_Python 3.x_Recursion_String Formatting - Fatal编程技术网

Python 3.x 为什么我的递归函数不是串接字符串?

Python 3.x 为什么我的递归函数不是串接字符串?,python-3.x,recursion,string-formatting,Python 3.x,Recursion,String Formatting,我正在编写一个递归函数来向后打印字符串。我想知道为什么返回语句的字符串格式不起作用?我正在使用python 3.7。 如果有人能告诉我为什么我不能编写下面这样的递归函数,那将非常有帮助 def back(word): if len(word)>1: print (word[-1] + (back(word[:len(word)-1])), end="") elif len(word)==1: return word

我正在编写一个递归函数来向后打印字符串。我想知道为什么返回语句的字符串格式不起作用?我正在使用python 3.7。 如果有人能告诉我为什么我不能编写下面这样的递归函数,那将非常有帮助

def back(word):

    if len(word)>1:

        print (word[-1] + (back(word[:len(word)-1])), end="")
    elif len(word)==1:
        return word
    else:
        print ("end")


back("stack")
正如khelwood在评论中提到的,执行
print()
不能代替
返回

解决您的问题的方法是:

def back(word):
ln=len(字)
如果ln>1:
wmo=单词[-1]
#已将print()更改为返回
返回(wmo+(返回(单词[:len(单词)-1]))
elif ln==1:
回信
其他:
打印(“结束”)
#将函数返回的值更改为print()
打印(背面(“堆叠”))
正如您在上面看到的,在固定解决方案中,我们从函数返回值并在外部打印它


希望这有帮助

印刷和退货是两码事。函数仅在获取长度为1的字符串时返回任何内容。否则它会打印某些内容而不是返回。是否需要使用递归函数?反转字符串的最简单方法是
print(word[:-1])
是的,我使用的是递归函数