简体   繁体   English

python替换字符串忽略换行

[英]python replace string ignore new line

For example , 例如 ,

str="dddabc
d
e
xxxx
123
345"

,want to replace "abcde" with null . ,想要将null替换为"abcde" New str need to be 需要新的str

"ddd
xxxx
123
345"

What is the easy way to do it ? 简单的方法是什么?

If I drop the new line , the new string will be dddxxxx123345 , and that wrong 如果我删除新行,则新字符串将为dddxxxx123345 ,这是错误的

This need to be on linux so it \\r\\n maybe 这需要在Linux上,所以\\r\\n

Use regex re.sub 使用正则表达式re.sub

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. 返回通过用替换repl替换字符串中最左边的非重叠模式所获得的字符串。 If the pattern isn't found, string is returned unchanged. 如果找不到该模式,则返回的字符串不变。 repl can be a string or a function; repl可以是字符串或函数; 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))

OUTPUT 输出值

ddd
xxxx
123
345

按以下方式使用正则表达式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM