0

I am getting the error:

AttributeError: 'str' object has no attribute 'append'

However, none of the posts on SO seem to be pertinent to my error. My issue is that I have no idea where my piece of code turns what seems to be an array into a string when appending.

Code:

import os
import hashlib
yn = True
var = []

while yn == True:
    print """
    1. Import from file
    2. Add new cards
    3. Look at the cards
    4. Delete cards  
    5. Modify cards  
    """
    ui = int(raw_input("Which option would you like to choose: "))
    if ui == 1:
        print "The directory is", os.getcwd()
        getcwdui = raw_input("Would you like to change the directory y/n: ")
        if getcwdui == "y":
            os.chdir(raw_input("Where would you like to change it to? Please make sure to include all necessary punctuation: "))
        else:
            print "\n"
        fileui = raw_input("Which file would you like to import?")
        file1 = open(fileui, "r")
        var = file1.read()
        var.split("]")
        file1.close()

#   [id, name, hp, set, setnum, rarity]
if ui == 2:
    name = raw_input("What is the name of the pokemon: ")
    hp = int(raw_input("What is the hp of the pokemon: "))
    setp = raw_input("What is the set of the pokemon: ")
    setnum = int(raw_input("What is the set number of the pokemon: "))
    rarity = raw_input("What is the rarity of the pokemon: ")
    copies = int(raw_input("How many copies of the card do you have: "))
    m = hashlib.md5()
    hashid = m.update(str(setnum))
    var.append([hashid, name, hp, setp, setnum, rarity])
    file1 = open(raw_input("What file would you like to open: "), "w")
    file1.write(str(var))
    file1.close()

2 Answers 2

2

Your problem is with this line:

var.split("]")

Like all string methods, str.split does not work in-place because strings are immutable in Python. Instead, it returns a new object, which is a list in this case.

If you want the value of var to change, you need to manually reassign the name:

var = var.split("]")

Otherwise, var will still be a string when you get to this line:

var.append([hashid, name, hp, setp, setnum, rarity])

Since strings do not have an append method, an AttributeError is raised.

Sign up to request clarification or add additional context in comments.

Comments

0

The first part of the above answer works. You can fix the second part with +=:

var += [hashid, name, hp, setp, setnum, rarity]

I hope this helps!

1 Comment

this would basically do the same thing as .extend which is not the same as .append...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.