【问题标题】:Why does a call to `str(someList)` sometimes create an "array" of spaces?为什么调用 `str(someList)` 有时会创建一个空格“数组”?
【发布时间】:2015-11-03 03:44:29
【问题描述】:

playerList 包含两个Player 对象(分别调用str 属性"a""b"),Player 实现__str____repr__。当我将str(playerList) 连接到另一个字符串时,我希望该字符串会附加"[a, b]" 形式的内容。相反,结果字符串会附加"[ , ]"。我犯了什么错误导致了这个结果?

这是我写的

prompt = "And then choose the opponent you would like to attack from " + str(playerList)

def __str__ (self):
    return self.name

def __repr__ (self):
    return str()

我在标准输出上得到了什么:

"And then choose the opponent you would like to attack from [, ]"

我想要什么:

"And then choose the opponent you would like to attack from [a,b]"

【问题讨论】:

  • 返回 str() ?不应该是 self.__str__ 吗?
  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。见:How to create a Minimal, Complete, and Verifiable example.
  • 希望更新顺利吗?

标签: python string list concatenation


【解决方案1】:

您的__repr__ 方法返回一个空字符串:

def __repr__(self):
    return str()

str() 不带参数是一个空字符串:

>>> str()
''

如果您想直接调用__str__,或者将self 传递给str()

return self.__str__()

return str(self)

请注意,将列表转换为字符串将包含该列表中的所有字符串作为它们的表示repr(stringobject) 的输出,它使用与创建此类字符串时相同的表示法。列表['a', 'b'] 将完全使用该符号转换为字符串:

>>> l = ['a', 'b']
>>> l
['a', 'b']
>>> str(l)
"['a', 'b']"
>>> print str(l)
['a', 'b']

如果你真的想包含那些字符串没有引号,你需要自己格式化:

>>> '[{}]'.format(', '.join([str(elem) for elem in l]))
'[a, b]'
>>> print '[{}]'.format(', '.join([str(elem) for elem in l]))
[a, b]

【讨论】:

  • 也许你可以解释一下,当解释器显示一个列表时,它会显示列表中每个项目的 repr,因此[, ] 是一个二元素列表。
  • 我就是这么说的:)
  • @Robᵩ:是的,但是我的班车到了我的站点,所以我不得不先出去走一小会儿。 :-)
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 2020-01-18
  • 2022-01-06
  • 2021-08-09
  • 1970-01-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多