Python Forum
Help? I can't figure this out.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help? I can't figure this out.
#1
If a line in my program contains the word murder, how can I get my program to replace the word murder with "-------")?
import sys


file = input('Enter the file name: ')
print()

try:
    fhand = open(file)
    
except:
    print('File cannot be opened:', file)
    sys.exit()
    
for line in fhand:
    if line == '\n':
        continue
    line = line.strip()
    print(line.upper())
Reply
#2
replace all  code betweel try ... except with
with open(file) as f:
   line = f.readlines()
   if 'murder' in line:
       line = line.replace('murder', '------')
   ... do stuff with line ...
also remove for line in fhand:
and move the rest up to the ... do stuff ... line above
Reply
#3
Will fix everything, I'll post my code here in a second.
Reply
#4
(May-24-2017, 05:22 PM)Larz60+ Wrote:
with open(file) as f:
.....

... still may cause the exception - if the file in question does not exist.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#5
Larz60+'s code will do the job more or less for homework assignment, but it will also substitute parts of words like murderer, murders, etc.
just a warning...
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020