代码之家  ›  专栏  ›  技术社区  ›  Mauro Gentile

删除regex后不需要的空格

  •  -1
  • Mauro Gentile  · 技术社区  · 8 年前

    我有一组字符串,如下所示:

    t='Enter  FLAVIUS ,                         MURELLUS , a  CARPENTER , a
                             COBBLER , and certain other
                         COMMONERS  over the stage    !  '
    

    i、 e.具有多个空格的字符串。 如果应用以下正则表达式,我可以将多个空间转换为一个空间,这就是我想要的:

    re.sub(' +',' ',t)
    OUTPUT: 'Enter FLAVIUS , MURELLUS , a CARPENTER , a COBBLER , and certain other COMMONERS over the stage !'
    

    我现在需要去掉单词和标点符号之间不必要的空格。

    换句话说,我希望输出为:

    OUTPUT: 'Enter FLAVIUS, MURELLUS, a CARPENTER, a COBBLER, and certain other COMMONERS over the stage!'
    

    我该怎么做?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Jay Shankar Gupta    8 年前
    import re
    t='Enter  FLAVIUS ,                         MURELLUS , a  CARPENTER , a                         COBBLER , and certain other                     COMMONERS  over the stage    !  '
    print(re.sub('\s+(?=[!,])','',re.sub(' +',' ',t)))
    

    输出

    Enter FLAVIUS, MURELLUS, a CARPENTER, a COBBLER, and certain other COMMONERS over the stage!