为什么调用`str(someList)`有时会创建一个空格的"数组"?

Mun*_*uno 0 python string list concatenation

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()
Run Code Online (Sandbox Code Playgroud)

我在stdout上得到了什么:

"And then choose the opponent you would like to attack from [, ]"
Run Code Online (Sandbox Code Playgroud)

我想要的是:

"And then choose the opponent you would like to attack from [a,b]"
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

def __repr__(self):
    return str()
Run Code Online (Sandbox Code Playgroud)

str() 没有参数是一个空字符串:

>>> str()
''
Run Code Online (Sandbox Code Playgroud)

如果你想__str__直接打电话,或传递selfstr():

return self.__str__()
Run Code Online (Sandbox Code Playgroud)

要么

return str(self)
Run Code Online (Sandbox Code Playgroud)

请注意,将列表转换为字符串将包括该列表中的所有字符串作为其表示 ; 输出repr(stringobject),使用您在创建此类字符串时使用的相同表示法.该列表['a', 'b']将使用该表示法转换为字符串:

>>> l = ['a', 'b']
>>> l
['a', 'b']
>>> str(l)
"['a', 'b']"
>>> print str(l)
['a', 'b']
Run Code Online (Sandbox Code Playgroud)

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

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