Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何删除花括号之间的文本_String_Python 3.x - Fatal编程技术网

String 如何删除花括号之间的文本

String 如何删除花括号之间的文本,string,python-3.x,String,Python 3.x,我从csv文件中提取了字符串。我想知道如何使用Python删除字符串中花括号之间的文本,例如: string = 'some text hear { bracket } some text here' 我想得到: some text hear some text here 我希望任何人都能帮我解决这个问题,谢谢 编辑: 回答 进口稀土 字符串='一些文本听到{括号}一些文本在这里' string=re.sub(r“\s*{.}\s”,“”,string) 打印(字符串)如下: import

我从csv文件中提取了字符串。我想知道如何使用Python删除字符串中花括号之间的文本,例如:

string = 'some text hear { bracket } some text here'
我想得到:

some text hear some text here
我希望任何人都能帮我解决这个问题,谢谢

编辑: 回答 进口稀土 字符串='一些文本听到{括号}一些文本在这里' string=re.sub(r“\s*{.}\s”,“”,string) 打印(字符串)

如下:

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

您应该为此使用正则表达式:

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
鉴于:

您可以使用
str.partition
str.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'

这只会替换
{word}
的精确匹配,而不会替换任何括在花括号中的子字符串。很好!谁知道呢?如果您知道需要替换什么,这将不必要地加载
re
模块,并且比字符串上的
replace
方法慢得多。您也可以这样做:
print(s.split('{')[0],s.split('}')[1])
>>> 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'