简体   繁体   中英

Remove all lines containing a certain word

Having a string like this one:

AAAA AAAA
BBBB BBBB
CCCC CCCC
DDXD DDDD
EEEE EEEE
FXFF RRRR

How could I remove all the lines containing an "X"?

I know that I could do it from a txt file, but I would like to do it directly from the string...

The result must be:

AAAA AAAA
BBBB BBBB
CCCC CCCC
EEEE EEEE

I tried with:

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

Try this:

with open("file.txt", "r") as f:
    lines = f.readlines()
with open("file.txt", "w") as f:
    for line in lines:
        if not "X" in line:
            f.write(line)

You can easily accomplish this by using list comprehension. Iterate through your string (split by \n ) and if a row is spotted without an X , then append it to a list.

stringRemoval = "AAAA AAAA\nBBBB BBBB\nCCCC CCCC\nDDXD DDDD\nEEEE EEEE\nFXFF RRRR"
cleanString = [line for line in stringRemoval.split('\n') if 'X' not in line]

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