看起来你只是想将一个字符串添加到字符串列表中。那就使用append
函数:
>>> inside = ['thing', 'other thing']
>>> inside.append('another thing')
>>> inside
['thing', 'other thing', 'another thing']
这里并没有特定的字符串内容;同样适用于Item
实例列表,或者字符串列表的列表,或者37个不同类型的37个不同事物的列表。
一般来说,append
是将单个事物连接到列表末尾的最有效方法。如果您想要连接一堆事物,并且已经将它们放在列表(或迭代器或其他序列)中,请使用extend
一次完成所有操作,或者只需使用+=
即可(对于列表而言,与extend
的含义相同):
>>> inside = ['thing', 'other thing']
>>> in_hand = ['sword', 'lamp']
>>> inside += in_hand
>>> inside
['thing', 'other thing', 'sword', 'lamp']
如果您想将字符串列表后来连接成一个字符串,可以使用 join
方法,正如 RocketDonkey 所解释的那样:
>>> ', '.join(inside)
'thing, other thing, another thing'
我猜你想要更加高级的效果,比如在最后两个元素之间加上“和”字,如果少于三个元素则跳过逗号等。但如果你知道如何切片列表和使用
join
函数,我认为可以留给读者自己练习。
如果你试图将列表连接成字符串,你需要以某种方式将该列表转换为字符串。你可以使用
str
函数,但通常这不会给你想要的结果,你可能需要像上面的
join
示例一样的东西。
无论如何,一旦你有了字符串,就可以将其添加到另一个字符串中。
>>> 'Inside = ' + str(inside)
"Inside = ['thing', 'other thing', 'sword', 'lamp']"
>>> 'Inside = ' + ', '.join(inside)
'Inside = thing, other thing, another thing'
如果您有一系列不是字符串的东西,并想将它们添加到字符串中,那么您需要决定这些东西的适当字符串表示形式(除非您满意于使用 repr
):
>>> class Item(object):
... def __init__(self, desc):
... self.desc = desc
... def __repr__(self):
... return 'Item(' + repr(self.desc) + ')'
... def __repr__(self):
... return self.desc
...
>>> inside = [Item('thing'), Item('other thing')]
>>> 'Inside = ' + repr(inside)
... "Inside = [Item('thing'), Item('other thing')]"
>>> 'Inside = ' + str(inside)
... "Inside = [Item('thing'), Item('other thing')]"
>>> 'Inside = ' + ', '.join(str(i) for i in inside)
... 'Inside = thing, other thing'
请注意,仅调用列表中的
Item
s上的
str
会调用个别项上的
repr
; 如果您想在它们上调用
str
,必须明确执行; 这就是
str(i) for i in inside
部分的作用。
将所有内容组合在一起:
class Backpack:
def __init__(self):
self.inside = []
def add(self, toadd):
self.inside.append(toadd)
def addmany(self, listtoadd):
self.inside += listtoadd
def __str__(self):
return ', '.join(str(i) for i in self.inside)
pack = Backpack()
pack.add('thing')
pack.add('other thing')
pack.add('another thing')
print 'Your backpack contains:', pack
当你运行此代码时,它将打印出以下内容:
Your backpack contains: thing, other thing, another thing
add
方法接受一个self
参数... - abarnert