简体   繁体   中英

why am i getting the attribute error?

The aim of my code is for the user to enter the sentence, ask for a position and then the whole thing to be read to one/two files, ie the positions and the words.

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()

That's my code, however I am getting this error

position.write(positionofword + " ")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Bear in mind that the word file is empty as well.

You code fails at position.write(positionofword + " ") , as positionofword is an integer and " " is a string, and python does not support adding integers to strings directly.

Use str() to convert positionofword to string:

position.write(str(positionofword) + " ")

The error is that the interpreter of python is reading the type of the interger first and then the + " " part. This produces an error as the interpreter is trying to use the integer add function which does not support the addition of a string.

You have to specifically tell the python interpreter that you want to use the string addition (concatenation) function.

position.write(str(positionofword) + " ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM