Answer
Your problem can be solved by a regex:
Put this into the shell:
import re
a=re.compile("<.*?>")
a.sub('',"Keep this part of the string< Remove this part>Keep This part as well")
Output:
'Keep this part of the stringKeep This part as well'
Second question:
import re
re.compile("
.*?\..{3}")
a.sub('',"Hello
Filename.png")
Output:
'Hello'
Breakdown
Regex is a robust way of finding, replacing, and mutating small strings inside bigger ones, for further reading,consult https://docs.python.org/3/library/re.html. Meanwhile, here are the breakdowns of the regex information used in this answer:
.
means any char.
*?
means as many of the before as needed but as little as possible(non-greedy match)
So .*?
means any number of characters but as little as possible.
Note: The reason there is a \.
in the second regex is that a .
in the match needs to be escaped by a
, which in its turn needs to be escaped as \
The methods:
re.compile(patten:str)
compiles a regex for farther use.
regex.sub(repl:str,string:str)
replaces every match of regex
in string
with repl.
Hope it helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…