简体   繁体   English

python 2.7删除括号

[英]python 2.7 remove brackets

I have a string opening with { and closing with } . 我有一个以{开头和以}结尾的字符串。 This brackets are always at first and at last and must appear, they can not appear in the middle. 此方括号始终始终在头和尾,并且必须出现,不能出现在中间。 as following: 如下:

{-4,10746,.....,205}

{-3,105756}

what is the most efficient way to remove the brackets to receive: 除去要接收的括号的最有效方法是什么:

-4,10746,.....,205
-3,105756
s[1:-1]     # skip the first and last character

You can also use replace method. 您也可以使用replace方法。

In [1]: a = 'hello world'

In [3]: a.replace('l','')
Out[3]: 'heo word'

Since you were not clear there are two possibilities it may be a string or a set 由于您不清楚,有两种可能,可能是字符串或集合

If it is a set this might work: 如果它是集合,则可能起作用:

a= {-4, 205, 10746}

",".join([str(s) for s in a])
output='10746,-4,205'

If it is a string this will work: 如果是字符串,它将起作用:

a= '{-4, 205, 10746}'
a.replace("{","").replace("}","")
output= '-4, 205, 10746'

Since there is no order in set the output is that way 由于没有设置顺序,因此输出是这样

Here's a rather roundabout way of doing exactly what you need: 这是一种完全满足您需要的回旋方式:

l = {-3,105756}
new_l = []
for ch in l:
    if ch!='{' and ch!= '}':
       new_l.append(ch)

for i,val in enumerate(new_l):
    length = len(new_l)
    if(i==length-1):
        print str(val)
    else:
        print str(val)+',',

I'm sure there are numerous single line codes to give you what you want, but this is kind of what goes on in the background, and will also remove the braces irrespective of their positions in the input string. 我确定有很多单行代码可以为您提供所需的内容,但这是在后台进行的操作,并且不管括号在输入字符串中的位置如何,括号都将被删除。

Just a side note, answer by @dlask is good to solve your issue. 只是附带说明,@ dlask的回答很好地解决了您的问题。

But if what you really want is to convert that string (that looks like a set) to a set object (or some other data structure) , you can also use ast.literal_eval() function - 但是,如果您真正想要的是将该字符串(看起来像一个集合)转换为集合对象(或其他数据结构),则还可以使用ast.literal_eval()函数-

>>> import ast
>>> s = '{-3,105756}'
>>> sset = ast.literal_eval(s)
>>> sset
{105756, -3}
>>> type(sset)
<class 'set'>

From documentation - 文档 -

ast.literal_eval(node_or_string) ast.literal_eval(node_or_string)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. 安全地评估包含Python文字或容器显示的表达式节点或Unicode或Latin-1编码的字符串。 The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. 提供的字符串或节点只能由以下Python文字结构组成:字符串,数字,元组,列表,字典,布尔值和无。

最安全的方法是剥离:

'{-4, 205, 10746}'.strip("{}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM