Python Forum
Help? I can't figure this out. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help? I can't figure this out. (/thread-3451.html)



Help? I can't figure this out. - hentera - May-24-2017

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())



RE: Help? I can't figure this out. - Larz60+ - May-24-2017

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


RE: Help? I can't figure this out. - hentera - May-24-2017

Will fix everything, I'll post my code here in a second.


RE: Help? I can't figure this out. - volcano63 - May-24-2017

(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.


RE: Help? I can't figure this out. - buran - May-24-2017

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...