2

For example ,

str="dddabc
d
e
xxxx
123
345"

,want to replace "abcde" with null . New str need to be

"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

This need to be on linux so it \r\n maybe

2 Answers 2

3

Use regex re.sub

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))

OUTPUT

ddd
xxxx
123
345
Sign up to request clarification or add additional context in comments.

3 Comments

@devohourse I have made the changes , earlier I didnt use raw strings now I did. That caused the error :-).
that but wtill I get same error , maybe because that need to work on linux and there break line is \r\n ?
@devohourse line break is always \n now if you are unsure about this type print(repr(string)) to print the underlying representation
1

Use regex as so :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.