Python Forum

Full Version: Help? I can't figure this out.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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())
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
Will fix everything, I'll post my code here in a second.
(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.
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...