python替换字符串忽略新lin

2024-05-15 06:07:19 发布

您现在位置:Python中文网/ 问答频道 /正文

例如

str="dddabc
d
e
xxxx
123
345"

,要将"abcde"替换为null。 新的str需要

"ddd
xxxx
123
345"

最简单的方法是什么?你知道吗

如果我删除新行,新字符串将是dddxxxx123345,这是错误的

这需要在linux上,所以它\r\n可能


Tags: 方法字符串linux错误nullstrdddxxxx
2条回答

使用正则表达式^{}

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed.

import re
st="""dddabc
d
e
xxxx
123
345
"""
rep="abcde"
print(re.sub(r'\n?'.join(rep),r'',st))

输出

ddd
xxxx
123
345

使用regex如下:

new_str = re.sub('a(\s)*b(\s)*c(\s)*d(\s)*e(\s)*', "", str)

相关问题 更多 >

    热门问题