首页 > 解决方案 > 字符串索引超出范围/无效语法

问题描述

我在命令行中运行代码时出现“字符串索引超出范围”错误,而它给出了“无效语法”,因为 VS 代码终端中的错误是我的代码

def copy(lst1, lst2 = []):
    if lst1==[]:
        return lst2
    else:
        lst2.append(lst1[0])
        copy(lst1[1:],lst2)                       #recursively calling of copy function

    return lst2
def main():
    lst1= input("Enter the string >> ")
    lst2 = copy(lst1)                             #calling of copy function
    print("The copied list is ", lst2)
main()                                            #calling of main function

标签: python-3.xlistrecursion

解决方案


lst1 是一个字符串,lst2 是一个列表。递归的终止条件根据一个空列表检查 lst1。但是空列表和空字符串是不一样的,所以终止条件检查不起作用。

>>> "" == []
False

推荐阅读