【问题标题】:Partitioning a string in Python by a regular expression通过正则表达式在 Python 中对字符串进行分区
【发布时间】:2011-05-09 03:00:30
【问题描述】:

我需要在字边界(空格)上将字符串拆分为数组,同时保留空格。

例如:

'this is  a\nsentence'

会变成

['this', ' ', 'is', '  ', 'a' '\n', 'sentence']

我知道str.partitionre.split,但它们都没有完全按照我的意愿行事,也没有re.partition

我应该如何在 Python 中以合理的效率在空格上划分字符串?

【问题讨论】:

    标签: python regex split whitespace


    【解决方案1】:

    试试这个:

    s = "this is  a\nsentence"
    re.split(r'(\W+)', s) # Notice parentheses and a plus sign.
    

    结果是:

    ['this', ' ', 'is', '  ', 'a', '\n', 'sentence']
    

    【讨论】:

    • 谢谢。我应该更仔细地阅读re.split 文档。
    【解决方案2】:

    re 中的空格符号是 '\s' 而不是 '\W'

    比较:

    import re
    
    
    s = "With a sign # written @ the beginning , that's  a\nsentence,"\
        '\nno more an instruction!,\tyou know ?? "Cases" & and surprises:'\
        "that will 'lways unknown **before**, in 81% of time$"
    
    
    a = re.split('(\W+)', s)
    print a
    print len(a)
    print
    
    b = re.split('(\s+)', s)
    print b
    print len(b)
    

    生产

    ['With', ' ', 'a', ' ', 'sign', ' # ', 'written', ' @ ', 'the', ' ', 'beginning', ' , ', 'that', "'", 's', '  ', 'a', '\n', 'sentence', ',\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction', '!,\t', 'you', ' ', 'know', ' ?? "', 'Cases', '" & ', 'and', ' ', 'surprises', ':', 'that', ' ', 'will', " '", 'lways', ' ', 'unknown', ' **', 'before', '**, ', 'in', ' ', '81', '% ', 'of', ' ', 'time', '$', '']
    57
    
    ['With', ' ', 'a', ' ', 'sign', ' ', '#', ' ', 'written', ' ', '@', ' ', 'the', ' ', 'beginning', ' ', ',', ' ', "that's", '  ', 'a', '\n', 'sentence,', '\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction!,', '\t', 'you', ' ', 'know', ' ', '??', ' ', '"Cases"', ' ', '&', ' ', 'and', ' ', 'surprises:that', ' ', 'will', ' ', "'lways", ' ', 'unknown', ' ', '**before**,', ' ', 'in', ' ', '81%', ' ', 'of', ' ', 'time$']
    61
    

    【讨论】:

      【解决方案3】:

      试试这个:

      re.split('(\W+)','this is  a\nsentence')
      

      【讨论】:

        猜你喜欢
        • 2015-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-30
        • 1970-01-01
        • 2013-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多