简体   繁体   中英

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.

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.

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 -

>>> 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)

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

最安全的方法是剥离:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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