将内容添加到python 3中字符串中每个(非空白)行的末尾

时间:2018-01-07 19:57:57

标签: python regex string replace

假设我有以下字符串:

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'。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

你真的需要正则表达式吗?您可以拆分换行符,相应地添加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
)