How remove the text between curly bracket

Viewed 3550

I have strings extracted from a csv file. I want to know how to remove the text between the curly brackets from the string using Python, ex:

string = 'some text hear { bracket } some text here'

I want to get:

some text hear some text here

I hope anyone can help me to solve this problem, thank you.

EDIT: answer import re string = 'some text hear { bracket } some text here' string = re.sub(r"\s*{.}\s", " ", string) print(string)

4 Answers

Given:

>>> s='some text here { bracket } some text there'

You can use str.partition and str.split:

>>> parts=s.partition(' {')
>>> parts[0]+parts[2].rsplit('}',1)[1]
'some text here some text there'

Or just partition:

>>> p1,p2=s.partition(' {'),s.rpartition('}')
>>> p1[0]+p2[2]
'some text hear some text there'

If you want a regex:

>>> re.sub(r' {[^}]*}','',s)
'some text hear some text there'

Like this:

import re
re.sub(r"{.*}", "{{}}", string)
>>> s = 'some text here { word } some other text'
>>> s.replace('{ word }', '')
    'some text here  some other text'

You could use a regular expression for this:

import re
string = 'some text hear { bracket } some text here'
string = re.sub(r"\s*{.*}\s*", " ", string)
print(string)

Output:

some text hear some text here
Related