python - 我需要让用户输入报价。通过空格将引用拆分为单个单词。在新行上显示每个单词
问题描述
quote=input("Enter a quote ")
split=quote.split(quote)
for count in range(0,(split)+1):
print(split)
我试过这样做,但给了我错误:for count in range(0,(split)+1): TypeError: can only concatenate list (not "int") to list
解决方案
您收到错误是因为您的split
变量是一个列表,并且您正在将+ 1
(这是一个整数)添加到您无法在 Python 中执行的列表中,因此TypeError
抛出 a 因为这两种类型与+
运算符不兼容而 Python 不兼容知道要做什么。
修复错误
代码存在一些问题会导致该错误被抛出以及一些小的逻辑问题:
- 您需要确保您是按空格而不是字符串本身来拆分字符串。
- 您还需要在 for 循环中获取字符串中单词列表的长度。
- 在循环中,您需要确保输出的是每个单词,而不是整个列表
有关更多详细信息,请参见下面的代码:
quote=input("Enter a quote ")
# Make sure to split by " " character
split=quote.split(" ")
# Make sure to get the length of the list of words in the split variable
for count in range(0, len(split)):
# Print each word, not the whole array
print(split[count])
希望有帮助;)
推荐阅读
- android - 是否有一个 android 图形 api 可以安全地重用图像缓冲区?
- ios - 如何加载多个网页并在它们之间切换?
- angular - 量角器:CRUD 操作
- rust - 通过使用来自 lib.rs 的模块 use crate::module
- r - 如何使用 R 中的半监督朴素贝叶斯预测未标记数据集的响应变量?
- javascript - 如何停止二叉搜索树遍历?
- javascript - 使用 inner.HTML 从给定数组创建表
- naudio - DirectSoundOut 不起作用,但 WaveOut 起作用
- reactjs - 如何在 GitHub 页面上部署我的 React 应用程序,使我的部署与“someName.github.io”完全一样
- r - 在 R 中使用 lmap 将函数应用到列表时出错