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

在python 3中,将内容添加到字符串中每一行(非空白)的末尾,python,regex,string,replace,Python,Regex,String,Replace,假设我有以下字符串: s = 'some text\n\nsome other text' 现在,我想将字母“X”添加到包含文本的每一行末尾,以便输出为“一些textX\n\n一些其他textX”。我试过了 re.sub('((?!\S)$)', 'X', s, re.M) 但这只会在字符串末尾添加'X',即使它处于多行模式,也就是说,输出是'some text\n\n some other textX'。我怎样才能解决这个问题 你真的需要正则表达式吗?您可以在换行符上拆分,相应地添加X,然

假设我有以下字符串:

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

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

但这只会在字符串末尾添加
'X'
,即使它处于多行模式,也就是说,输出是
'some text\n\n some other textX'
。我怎样才能解决这个问题

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

作为参考,这是如何使用regex实现的-

Out[507]: re.sub(r'(?<=\S)(?=\n|$)', r'X', s, re.M)
Out[507]: 'some textX\n\nsome other textX'
Out[507]:re.sub(r'(?)?
(?<=    # lookbehind
\S      # anything that is not a whitespace character, alt - `[^\n]`
)
(?=     # lookahead
\n      # newline
|       # regex OR
$       # end of line
)