无法将'list'对象转换为str隐式python

时间:2013-12-04 11:22:42

标签: python string list

elif used_prefix and cmd == "xp":
            if self.getAccess(user) >= 1:
                f = open("users/" + user.name.lower() + ".txt", 'r')
                word = f.readline().split("X Points = ")
                if word == "0":
                        room.message("You have no X Points")
                else:
                    room.message("You Have " + word + " X Points")
                f.close()
            else:
                room.message("You are not whitelisted " + user.name.capitalize())

当我尝试使用XP时,它会在控制台中显示Can't convert 'list' object to str implicitly错误。我正在使用python 3.3。

2 个答案:

答案 0 :(得分:3)

您可能需要

word = f.readline().split("X Points = ")[1].strip()

在拆分时,它将返回拆分为列表的项目列表。您需要获取与实际值相对应的元素

示例

data = "X Points = 10"
print data.split("X Points = ")

<强>输出

['', '10']

所以,我们需要得到第二个元素。这就是为什么我们使用[1]

答案 1 :(得分:0)

主要问题是split会返回一个列表,而不是一个字符串。

if self.getAccess(user) >= 1:
    with open("users/{}.txt".format(user.name.lower()), 'r') as f:
         word = f.readline().split("X Points = ")[1]
    if word == "0":
         room.message("You have no X Points")
    else:
         room.message("You Have {} X Points".format(word))
else:
    room.message("You are not whitelisted {}".format(user.name.capitalize()))