Print list without brackets in a single row

2019-01-01 12:52发布

I have a list in Python e.g.

names = ["Sam", "Peter", "James", "Julian", "Ann"]

I want to print the array in a single line without the normal " []

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)

Will give the output as;

["Sam", "Peter", "James", "Julian", "Ann"]

That is not the format I want instead I want it to be like this;

Sam, Peter, James, Julian, Ann

Note: It must be in a single row.

标签: python list
8条回答
裙下三千臣
2楼-- · 2019-01-01 13:07
print(', '.join(names))

This, like it sounds, just takes all the elements of the list and joins them with ', '.

查看更多
美炸的是我
3楼-- · 2019-01-01 13:07

Here is a simple one.

names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names, sep=", ")

the star unpacks the list and return every element in the list.

查看更多
伤终究还是伤i
4楼-- · 2019-01-01 13:09

This is what you need

", ".join(names)
查看更多
与风俱净
5楼-- · 2019-01-01 13:19

There are two answers , First is use 'sep' setting

>>> print(*names, sep = ', ')

The other is below

>>> print(', '.join(names))
查看更多
零度萤火
6楼-- · 2019-01-01 13:24

General solution, works on arrays of non-strings:

>>> print str(names)[1:-1]
'Sam', 'Peter', 'James', 'Julian', 'Ann'
查看更多
后来的你喜欢了谁
7楼-- · 2019-01-01 13:26

You need to loop through the list and use end=" "to keep it on one line

names = ["Sam", "Peter", "James", "Julian", "Ann"]
    index=0
    for name in names:
        print(names[index], end=", ")
        index += 1
查看更多
登录 后发表回答