【问题标题】:How remove the text between curly bracket如何删除大括号之间的文字
【发布时间】:2018-03-05 02:09:35
【问题描述】:

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

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

我想得到:

some text hear some text here

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

编辑: 回答 重新进口 string = '一些文字听到{括号}这里有一些文字' 字符串 = re.sub(r"\s*{.}\s", " ", 字符串) 打印(字符串)

【问题讨论】:

  • 你也可以这样做:print(s.split(' {')[0],s.split('} ')[1])

标签: string python-3.x


【解决方案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'

【讨论】:

    【解决方案2】:

    像这样:

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

    【讨论】:

    • 如果您知道需要替换什么,这将不必要地加载re 模块,并且比字符串上的replace 方法慢得多。
    【解决方案3】:
    >>> s = 'some text here { word } some other text'
    >>> s.replace('{ word }', '')
        'some text here  some other text'
    

    【讨论】:

    • 这将只替换 { word } 的完全匹配,但不会替换任何用大括号括起来的子字符串。
    • 好发现!谁知道?
    【解决方案4】:

    您可以为此使用正则表达式:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      相关资源
      最近更新 更多