代码之家  ›  专栏  ›  技术社区  ›  MaxCore

python:匹配并替换每行开头的所有空格

  •  2
  • MaxCore  · 技术社区  · 8 年前

    我需要这样转换文本:

    ' 1 white space before string'
    '  2 white spaces before string'
    '   3 white spaces before string'
    

    变成:

    ' 1 white space before string'
    '  2 white spaces before string'
    '   3 white spaces before string'
    

    单词和行尾之间的空格不应匹配,只应在行首匹配。而且,不需要匹配制表符。大号THX求救

    2 回复  |  直到 8 年前
        1
  •  3
  •   cs95 abhishek58g    8 年前

    使用 re.sub 具有执行实际替换的回调:

    import re
    
    list_of_strings = [...]
    
    p = re.compile('^ +')
    for i, l in enumerate(list_of_strings): 
        list_of_strings[i] = p.sub(lambda x: x.group().replace(' ', ' '), l)
    

    print(list_of_strings)
    [' 1 white space before string',
     '  2 white spaces before string',
     '   3 white spaces before string'
    ]
    

    这里使用的模式是 '^ +' 并将搜索和替换空白,只要它们位于字符串的开头。

        2
  •  2
  •   jedwards    8 年前

    如果你知道空格只是前导空格,你可以这样做:

    l = ' ' * (len(l) - len(l.lstrip())) + l.lstrip()
    

    但不是最有效率的。这样会好一点:

    stripped = l.strip()
    l = ' ' * (len(l) - len(stripped)) + stripped
    print(l)
    

    这是一种不用 re 头顶上。

    例如:

    lines = [
        ' 1 white space before string',
        '  2 white spaces before string',
        '   3 white spaces before string',
    ]
    
    for l in lines:
        stripped = l.strip()
        l = ' ' * (len(l) - len(stripped)) + stripped
        print(l)
    

    输出:

     1 white space before string
      2 white spaces before string
       3 white spaces before string