无法分配到函数调用

时间:2016-01-14 14:24:04

标签: python string python-3.x

我不明白为什么会发生这种情况..我认识的其他任何事都没有发生......到目前为止,这是我的代码

# creating a string which will be our main sentence
string = input("Please enter a sentence.\n")
str(string)
# creates a list and then splits the string up and puts all the parts into a list
stringlist = []
string.lower()
string = string.split()
stringlist.append(string)

# prints the list to check for any errors during splitting
print(stringlist)

find = input("Which word would you like to find?\n")

while find in stringlist:
    index = stringlist.index(find)
    stringlist(index) = ""
    indexpositions.append(str(index + 1))

我要做的是在一个句子中找到一个单词并找到它的所有索引。

2 个答案:

答案 0 :(得分:3)

您使用错误的括号来索引stringlist。你应该stringlist[index]=""

答案 1 :(得分:2)

我能找到的问题列表

  1. 在Python中,您需要使用[]访问列表的元素。因此,您需要将代码更改为

    stringlist[index] = ""
    indexpositions.append(str[index + 1])
    
  2. 除此之外,

    str(string)
    ...
    string.lower()
    

    是NOOP。第一行只是将string转换为字符串对象并立即将其丢弃,第二行只是将字符串转换为小写字符串并返回一个新的字符串对象,也会被忽略。可能你的意思是

    string = str(string)
    ...
    string = string.lower()
    

    此外,str(string)部分不是必需的,因为input函数仅返回字符串对象。

  3. 如果在列表中找不到该项,则另一个问题是,string.find会返回-1。在Python中,序列可以有负索引。所以,您可能也想知道这种情况。

  4. 所以你的代码可以像这样编写

    stringlist = input("Please enter a sentence.\n").lower().split()
    
相关问题