How to remove square brackets from list in Python? [duplicate]

▼魔方 西西 提交于 2019-11-26 12:12:20

问题


LIST = [\'Python\',\'problem\',\'whatever\']
print(LIST)

When I run this program I get

[Python, problem, whatever]

Is it possible to remove that square brackets from output?


回答1:


You could convert it to a string instead of printing the list directly:

print(", ".join(LIST))

If the elements in the list aren't strings, you can convert them to string using either repr (if you want quotes around strings) or str (if you don't), like so:

LIST = [1, "foo", 3.5, { "hello": "bye" }]
print( ", ".join( repr(e) for e in LIST ) )

Which gives the output:

1, 'foo', 3.5, {'hello': 'bye'}



回答2:


Yes, there are several ways to do it. For instance, you can convert the list to a string and then remove the first and last characters:

l = ['a', 2, 'c']
print str(l)[1:-1]
'a', 2, 'c'

If your list contains only strings and you want remove the quotes too then you can use the join method as has already been said.




回答3:


if you have numbers in list, you can use map to apply str to each element:

print ', '.join(map(str, LIST))

^ map is C code so it's faster than str(i) for i in LIST




回答4:


def listToStringWithoutBrackets(list1):
    return str(list1).replace('[','').replace(']','')


来源:https://stackoverflow.com/questions/13207697/how-to-remove-square-brackets-from-list-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!