2017-09-23 95 views
1

我從csv文件中提取字符串。我想知道如何使用Python去除字符串中的大括號中的文字,例如:如何刪除大括號中的文本

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

我想:

some text hear some text here 

我希望有人能幫助我解決這個問題, 謝謝。

編輯: 答案 進口重新 字符串= '一些文本聽到{}支架一些文字在這裏' 字符串=應用re.sub(R 「{} \ S * \ S」, 「」,字符串) 打印(串)

+0

你也可以像這樣:'打印(s.split( '{ ')[0],s.split('}')[1 ])' – tonypdmtr

回答

0

您應該使用正則表達式是:

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

輸出:

some text hear some text here 
0
>>> s = 'some text here { word } some other text' 
>>> s.replace('{ word }', '') 
    'some text here some other text' 
+0

這隻會取代'{word}'的精確匹配,而不是括在大括號中的任何子字符串。 –

+0

斑點!誰知道? –

0

像這樣:

import re 
re.sub(r"{.*}", "{{}}", string) 
+0

如果你知道你需要替換什麼,這將不必要地加載're'模塊,並且比字符串上的'replace'方法慢得多。 –

1

考慮:

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

您可以使用str.partitionstr.split

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

或者只是分區:

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

如果你想有一個正則表達式:

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