简体   繁体   中英

Python Remove all Lines starting with specific word

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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