首页 > 解决方案 > 我需要让用户输入报价。通过空格将引用拆分为单个单词。在新行上显示每个单词

问题描述

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

标签: python

解决方案


您收到错误是因为您的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])

希望有帮助;)


推荐阅读