Reputation: 27
The code i have right:
with open("text.txt") as openfile:
for line in openfile:
for part in line.split():
if "Hello" in part:
print(part)
Can only find a specific word like hello in the text an print it. The problem is, i want it to stop printing only that word and print the entire line that has the word in it. How can i do that?
This is the result im getting right now:
hello
hello
hello
Whreas, the text document includes:
hello, i am a code
hello, i am a coder
hello, i am a virus
Upvotes: 1
Views: 3267
Reputation: 1268
Pay attention that the word "hello" is LowerCase in your example, therefore, for catching also upper and lowercases I would recommend this modified piece of code:
with open("text.txt") as openfile:
for line in openfile:
if "hello" in line.lower():
print(line)
Upvotes: 3
Reputation: 707
You just do a non necessary for loop, try this:
with open("text.txt") as openfile:
for line in openfile:
if "Hello" in line:
print(line)
Upvotes: 5