获得AttributeError:' str'对象没有属性'追加'

时间:2014-12-19 02:56:59

标签: python string python-2.7 attributeerror

我收到错误:

  

AttributeError:'str'对象没有属性'append'

然而,SO上的帖子似乎都与我的错误无关。我的问题是我不知道我的代码片段在附加时将似乎是数组的数组转换为字符串。

代码:

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 个答案:

答案 0 :(得分:2)

你的问题在于这一行:

var.split("]")

与所有字符串方法一样,str.split不能就地工作,因为字符串在Python中是不可变的。相反,它返回一个 new 对象,在这种情况下是一个列表。

如果您想要更改var的值,则需要手动重新分配名称:

var = var.split("]")

否则,当您到达此行时,var仍然是一个字符串:

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

由于字符串没有append方法,因此会引发AttributeError

答案 1 :(得分:0)

上述答案的第一部分有效。您可以使用+=修复第二部分:

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

我希望这有帮助!