Suppose I have a string that contains:
ASFksdfasf a
Oh sadfafas
Yeasd: asdfaf
Oh asdfaf
And I want to delete the lines from the string that start with "Oh". How exactly would I approach this? Right now I know I can do something in regex similar to this:
\b[Oh]\S*
But I am unsure on how to store this result to a variable, and even then, I believe it only finds the words, not deletes them.
I commented on OP with the expression you'd use to do this, but suggested going with @AvinashRaj's answer (non-regex). You asked how this would be implemented, and re.sub() is the answer!
Demo:
string = '''ASFksdfasf a
Oh sadfafas
Yeasd: asdfaf
Oh asdfaf'''
import re
print re.sub(r'^Oh.*\n?', '', string, flags=re.MULTILINE)
Outputs:
ASFksdfasf a
Yeasd: asdfaf
Use string.startswith function.
if not string.startswith('Oh'):
Example:
>>> s = '''ASFksdfasf a
Oh sadfafas
Yeasd: asdfaf
Oh asdfaf'''
>>> for line in s.splitlines():
if not line.startswith('Oh'):
print(line)
ASFksdfasf a
Yeasd: asdfaf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With