python-3.x - 字符串索引超出范围/无效语法
问题描述
我在命令行中运行代码时出现“字符串索引超出范围”错误,而它给出了“无效语法”,因为 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
解决方案
lst1 是一个字符串,lst2 是一个列表。递归的终止条件根据一个空列表检查 lst1。但是空列表和空字符串是不一样的,所以终止条件检查不起作用。
>>> "" == []
False
推荐阅读
- docker - 使用 buildpacksio/pack 构建 Docker 映像时出现“无法获取构建器映像...无法在 unix 上连接到 Docker 守护程序”错误
- node.js - 使用 MarkLogic NodeJS 客户端中的持久查询选项获取建议
- stm32 - 在 STM32F1 Blue Pill 上的多个 USART 连接之间发出中继消息
- javascript - 如果一个人属于一个团队,MongoDB 的总回报
- vba - 自动从特定收件箱下载电子邮件附件,检测文件类型,重命名和删除电子邮件
- regression - SPSS最佳插补方法
- python - 如何使用 python 将数据从 csv 文件写入 MySQL 数据库?
- c# - 如何在 HP ALM C# OTA 中过滤 ID 范围内的缺陷
- javascript - 无法使用 Node.js 在 Selenium 中运行特定的 Firefox 配置文件
- python - 如何在熊猫数据框中选择每第四行并计算滚动平均值