如何从Python中的列表中删除方括号? [重复]

时间:2021-10-14 21:41:03

This question already has an answer here:

这个问题在这里已有答案:

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?

是否可以从输出中删除方括号?

4 个解决方案

#1


57  

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:

如果列表中的元素不是字符串,则可以使用repr(如果需要字符串周围的引号)或str(如果不需要)将它们转换为字符串,如下所示:

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


19  

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.

如果您的列表只包含字符串,并且您想要删除引号,那么您可以使用已经说过的join方法。

#3


11  

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

如果列表中有数字,则可以使用map将str应用于每个元素:

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

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

^ map是C代码,所以它比我在LIST中的str(i)更快

#4


5  

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

#1


57  

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:

如果列表中的元素不是字符串,则可以使用repr(如果需要字符串周围的引号)或str(如果不需要)将它们转换为字符串,如下所示:

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


19  

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.

如果您的列表只包含字符串,并且您想要删除引号,那么您可以使用已经说过的join方法。

#3


11  

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

如果列表中有数字,则可以使用map将str应用于每个元素:

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

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

^ map是C代码,所以它比我在LIST中的str(i)更快

#4


5  

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