有没有一种方法可以有效地连接str和list?
1 2 3 4 5 6 7 | inside = [] #a list of Items class Backpack: def add(toadd): inside += toadd print"Your backpack contains:" #now what do I do here? |
听起来好像您只是在尝试将字符串添加到字符串列表中。这就是
1 2 3 4 | >>> inside = ['thing', 'other thing'] >>> inside.append('another thing') >>> inside ['thing', 'other thing', 'another thing'] |
这里没有特定的字符串;对于
通常,
1 2 3 4 5 | >>> inside = ['thing', 'other thing'] >>> in_hand = ['sword', 'lamp'] >>> inside += in_hand >>> inside ['thing', 'other thing', 'sword', 'lamp'] |
如果你以后想把字符串列表连接成一个字符串,那就是
1 2 | >>> ', '.join(inside) 'thing, other thing, another thing' |
我猜你想要变得更漂亮一点,在最后一件事之间加上"and",如果少于3个,跳过逗号,等等。但是如果您知道如何分割列表以及如何使用
如果您正尝试以另一种方式将列表连接到字符串,则需要以某种方式将该列表转换为字符串。您可以只使用
无论如何,一旦你有了字符串,你可以把它添加到另一个字符串:
1 2 3 4 | >>> 'Inside = ' + str(inside) "Inside = ['thing', 'other thing', 'sword', 'lamp']" >>> 'Inside = ' + ', '.join(inside) 'Inside = thing, other thing, another thing' |
如果你有一个非字符串的列表,并想把它们添加到字符串中,你必须决定这些东西的适当字符串表示(除非你对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> 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' |
注意,只是在一个
综合起来:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
当你运行这个,它会打印:
1 | Your backpack contains: thing, other thing, another thing |
你可以试试这个:
1 2 3 4 5 6 | In [4]: s = 'Your backpack contains ' In [5]: l = ['item1', 'item2', 'item3'] In [6]: print s + ', '.join(l) Your backpack contains item1, item2, item3 |
与其他Python方法相比,
如果希望向
1 2 3 4 5 6 7 8 9 10 | In [11]: inside = [] In [12]: inside.append('item1') In [13]: inside.append('item2') In [14]: inside.append('item3') In [15]: print 'Your backpack contains ' + ', '.join(inside) Your backpack contains item1, item2, item3 |