2015-02-17 71 views
2

我有以下列表:如何将列表转换为多行字符串?

["Jargon", "Hello", "This", "Is", "Great"] 

我要填充的字符串:

""" 
{} 
""".format(list-elements-besides-the-first) 

有一个简单的一个班轮我可以用它来使,这样我可以:

  1. 获取数组的所有元素(除了第一个元素)并将其推入{}?
  2. 是否有可能使每个元素都显示在自己的行中?
+0

那你除了第一意思? – 2015-02-17 22:12:26

+0

你甚至不需要'格式'来做到这一点。 – ozgur 2015-02-17 22:18:24

回答

5
""" 
{} 
""".format("\n".join(items[1:])) 
3

您可以使用list slicingjoining,那就是:

yourList = ["Jargon", "Hello", "This", "Is", "Great"] 
butFirst = yourList[1:] 
eachInASeparateLine = "\n".join(butFirst) 

print eachInASeparateLine 
0

使用join()字符串列表slice方法的方法。

>>> l = ["Jargon", "Hello", "This", "Is", "Great"] 
>>> l[1:] 
['Hello', 'This', 'Is', 'Great'] 
>>> result = "\n".join(l[1:]) 
>>> print result 
Hello 
This 
Is 
Great 
>>> 
0

里面创建了 “{}”,然后用新的生产线加入他们与项目的新名单

test = ["Jargon", "Hello", "This", "Is", "Great"] 
group = '\n'.join([test[0]] + ['{'+item+'}' for item in test[1:]]) 
print(group) 

输出:

Jargon 
{Hello} 
{This} 
{Is} 
{Great} 
0

我不是绝对确定你在问什么,因为你的帖子不是非常简洁,但是这会打印每个项目,除了第一个项目NE:

lst = ["Jargon", "Hello", "This", "Is", "Great"] print '\n'.join([i for i in lst[1:]])

\n使用字符串中使用时,以使换行。使用列表切片在第一项之后对所有元素执行操作。使用for循环可以迭代所选索引内的所有元素。

输出: Hello This Is Great

+0

'[我为我在lst [1:]]'和'lst [1:]'之间有什么区别? – 2015-02-18 00:24:08

相关问题