Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

How to remove an entire string which has a word in it?

For example, I have the file that contains:

Cheese is nice

Ham is also pretty tasty

This is fun

How can I input, a string with the 'Ham' and it should be entirely deleted. So if I input the Ham it removes my entire string.

Ham is also pretty tasty

1 Answer

0 votes
by (36.8k points)

I think this is something you are asking for.

# Word that you are looking for

word = "Ham"

# Input file

input = open("file1.txt", "rt")

# Output file

output = open("file2.txt", "wt")

# Loops through each line in the input file

for line in input:

  # Checks if the word is in the line (Not case sensitive)

  if not (word.upper() in line.upper()):

    # Adds the line to the output file if the word is not found

    output.write(line)     

input.close()

output.close()

Want to be a master in Data Science? Enroll in this Data Science Courses 

Browse Categories

...