【发布时间】:2016-04-23 19:11:31
【问题描述】:
我正在尝试获取 StringProperty 的值(作为字符串)但没有成功。 我需要遍历它,如果我只是尝试遍历属性,它会引发错误,因为它不是可迭代的。 如何将 StringProperty 转换为 Python 字符串,或者转换为我可以迭代并具有 len 的字符串?
编辑:
这就是我声明有问题的种类的方式:
class Game(ndb.Model):
"""Game object"""
target = ndb.StringProperty(required=True)
attempts_allowed = ndb.IntegerProperty(required=True)
attempts_remaining = ndb.IntegerProperty(required=True, default=5)
game_over = ndb.BooleanProperty(required=True, default=False)
user = ndb.KeyProperty(required=True, kind='User')
users_word = ndb.StringProperty(required=True)
最后一个属性是我需要遍历的。这是引发错误的函数:
@classmethod
def update_users_word(self, letter):
word_as_list = list(self.users_word)
print ("String is: " + str(getattr(self, 'users_word')))
for pos in self.find_letter_positions_in_word(letter, self.target):
word_as_list[pos] = letter
self.users_word = ''.join(word_as_list)
这是确切的错误:
Number/models.py", line 59, in update_users_word
word_as_list = list(self.users_word)
TypeError: 'StringProperty' object is not iterable
希望现在更清楚
【问题讨论】:
-
寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。
-
一个StringProperty 是一个字符串,你可以迭代它。如果您遇到问题,您应该发布实际代码和错误。
-
read for comprehension specific problem or error and the shortest code necessary to reproduce.,因为你是唯一一个遇到这个问题的人,因为它是
str或unicode很可能是你的代码不正确。 -
所以这是stackoverflow.com/questions/27751418/… 的完全重复,按照之前的要求发布代码会让您更早得到答案。