string - 如何删除大括号之间的文本

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

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

我想得到:

some text hear some text here

希望有人能帮我解决这个问题,谢谢。

编辑: 回答

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

最佳答案

给定:

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

https://stackoverflow.com/questions/46382621/

相关文章:

php - 第 0 行未知中的警告 : Unknown: Failed to write sessi

jekyll - 如何使用 Jekyll 将 CSS 导入 SCSS 文件?

asp.net-mvc - ASP.NET Core 模型状态不返回 DataMember 名称

python - 使用矩阵作为鸭嘴兽 MOEA 的输入

html - 打印时将页脚放在底部

javascript - 使用 toLocaleTimeString() 以毫秒为单位显示时间

firebase - 我如何跟踪 firebase 和 bigquery 中的流行用户流?

dataframe - 通过 [PySpark] 列连接两个 DataFrame

reactjs - reactjs 应用程序中的全局 SASS 变量

html - 样式对象的内容/嵌入