aldegalan
aldegalan

Reputation: 502

Remove a line that contains a word from a list

Having a string like this one:

machine1 volumename1 space1
machine1 volumename2 space2
machine2 volumename1 space1
machine2 volumename2 space2
machine3 volumename1 space1

I would like to remove all the lines containing one element of a list, for example:

list = ["machine1", "machine3"]

Receiving at the end something like this:

machine2 volumename1 space1
machine2 volumename2 space2

I tried with this, but it returns a list, and I would like to not change the original format of the string and I would like to use a list of machines as an input:

output = str([line for line in output.split('\n') if 'machine1' not in line and 'machine3' not in line])

Upvotes: 1

Views: 719

Answers (3)

tripleee
tripleee

Reputation: 189397

Just '\n'.join() the list back together after filtering it.

output = '\n'.join(line for line in output.splitlines() if 'machine1' not in line and 'machine3' not in line)

If you are explicitly examining only the first field and the whole first field, the code will be both more precise and robust and possibly even faster if you explicitly split() out the first field and examine only that.

output = '\n'.join(line for line in ouput.splitlines()
    if line.split()[0] not in ['machine1', 'machine3'])

Upvotes: 2

LaytonGB
LaytonGB

Reputation: 1404

Use the any keyword to avoid any items from your list, and instead of converting to a string with str use "connector".join(list) as shown in the print function.

As a side-note, you really shouldn't use keywords like list to name your variables, so I've changed that variable name to lst.

output = """machine1 volumename1 space1
machine1 volumename2 space2
machine2 volumename1 space1
machine2 volumename2 space2
machine3 volumename1 space1"""
lst = ["machine1", "machine3"]

output = [line for line in output.split('\n') if not any(w in line for w in lst)]
print("\n".join(output))

Output:

machine2 volumename1 space1
machine2 volumename2 space2

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

Try using \n, and any for list:

lst = ["machine1", "machine3"]
print('\n'.join([line for line in output.splitlines() if not any(i in line for i in lst)]))

Output:

machine2 volumename1 space1
machine2 volumename2 space2

Upvotes: 3

Related Questions