【问题标题】:Add content to the end of each (non-whitespace) line in string in python 3在python 3中将内容添加到字符串中每个(非空白)行的末尾
【发布时间】:2018-01-07 19:57:56
【问题描述】:

假设我有以下字符串:

s = 'some text\n\nsome other text'

我现在想在包含文本的每一行的末尾添加字母“X”,以便输出为'some textX\n\nsome other textX'。我试过了

re.sub('((?!\S)$)', 'X', s, re.M)

但这只会在字符串末尾添加'X',即使它处于多行模式,即输出为'some text\n\nsome other textX'。我怎么解决这个问题?

【问题讨论】:

    标签: python regex string replace


    【解决方案1】:

    你真的需要正则表达式吗?您可以在换行符上拆分,相应地添加X,然后重新加入。这是一种方法,使用yield -

    In [504]: def f(s):
         ...:     for l in s.splitlines():
         ...:         yield l + ('X' if l else '')
         ...:         
    
    In [505]: '\n'.join(list(f(s)))
    Out[505]: 'some textX\n\nsome other textX'
    

    这是使用列表理解的替代方法 -

    In [506]: '\n'.join([x + 'X' if x else '' for x in s.splitlines()])
    Out[506]: 'some textX\n\nsome other textX'
    

    作为参考,这是您使用正则表达式执行此操作的方式 -

    Out[507]: re.sub(r'(?<=\S)(?=\n|$)', r'X', s, re.M)
    Out[507]: 'some textX\n\nsome other textX'
    

    您需要使用前瞻和后瞻。这是表达式的细分 -

    (?<=    # lookbehind
    \S      # anything that is not a whitespace character, alt - `[^\n]`
    )
    (?=     # lookahead
    \n      # newline
    |       # regex OR
    $       # end of line
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-06
      • 2016-07-20
      • 2017-04-10
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      相关资源
      最近更新 更多