为什么调用 `str(someList)` 有时会产生 "array" 个空格?
Why does a call to `str(someList)` sometimes create an "array" of spaces?
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]"
您的 __repr__
方法 returns 一个空字符串:
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]
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]"
您的 __repr__
方法 returns 一个空字符串:
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]