【问题标题】:Getting AttributeError: 'str' object has no attribute 'append'获取 AttributeError:'str' 对象没有属性 'append'
【发布时间】:2015-02-17 23:30:54
【问题描述】:

我收到错误:

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

【问题讨论】:

    标签: python string python-2.7 attributeerror


    【解决方案1】:

    你的问题在于这一行:

    var.split("]")
    

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

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

    var = var.split("]")
    

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      我希望这会有所帮助!

      【讨论】:

      • 这基本上与.extend 做同样的事情,这与.append 不同...
      猜你喜欢
      • 2015-03-08
      • 1970-01-01
      • 2020-12-18
      • 2018-05-16
      • 1970-01-01
      • 2019-03-31
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多