我的代碼的目的是讓用戶輸入句子,請求一個位置,然後整個事情被讀取到一個/兩個文件,即位置和單詞。爲什麼我得到屬性錯誤?
sentencelist=[] #variable list for the sentences
word=[] #variable list for the words
positionofword=[]
words= open("words.txt","w")
position= open("position.txt","w")
question=input("Do you want to enter a sentence? Answers are Y or N.").upper()
if question=="Y":
sentence=input("Please enter a sentance").upper() #sets to uppercase so it's easier to read
sentencetext=sentence.isalpha or sentence.isspace()
while sentencetext==False: #if letters have not been entered
print("Only letters are allowed") #error message
sentence=input("Please enter a sentence").upper() #asks the question again
sentencetext=sentence.isalpha #checks if letters have been entered this time
elif question=="N":
print("The program will now close")
else:
print("please enter a letter")
sentence_word = sentence.split(' ')
for (i, check) in enumerate(word): #orders the words
print(sentence)
sentence_words = sentence.split(' ')
word = input("What word are you looking for?").upper() #asks what word they want
for (i, check) in enumerate(sentence_words): #orders the words
if (check == word):
positionofword=print(str(("your word is in this position:", i+1)))
positionofword=i+1
break
else:
print("This didn't work")
words.write(word + " ")
position.write(positionofword + " ")
words.close()
position.close()
這是我的代碼,但我得到這個錯誤
position.write(positionofword + " ")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
記住,這個詞文件是空的爲好。
:
使用
str()
到positionofword
轉換爲字符串。你不能在一個int和一個字符串上使用'+'運算符 – SimonSimon所以我拿出'postionofword = i + 1'? – hana