Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Remove all Lines starting with specific word

Tags:

python

regex

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.

like image 343
user2677095 Avatar asked Aug 24 '26 16:08

user2677095


2 Answers

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
like image 125
Sam Avatar answered Aug 27 '26 06:08

Sam


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
like image 38
Avinash Raj Avatar answered Aug 27 '26 06:08

Avinash Raj