Very basic Python question (strings, formats and escapes)

后端 未结 10 2085
别那么骄傲
别那么骄傲 2021-02-06 10:59

I am starting to learn Python with an online guide, and I just did an exercise that required me to write this script:

from sys import argv

script, filename = ar         


        
10条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 11:44

    I am currently following the same course, and the solution I found was similar to the one ninjagecko used, except I only used the things you were taught up to this point in the course. Mine looks like this:

    from sys import argv
    script, filename = argv
    print "We're going to erase %s." % filename
    print "If you don't want that, hit CTRL-C (^C)."
    print "If you do want that, hit RETURN."
    
    raw_input("?")
    
    print "Opening the file..."
    target = open(filename, 'w')
    
    print "Truncating the file. Goodbye!"
    target.truncate()
    
    print "Now I'm going to ask you for three lines."
    
    lines = [raw_input("Lines %r :" % i) for i in range(1, 4)]
    
    for line in lines:
        target.write(line + "\n")
    
    print "And finally, we close it."
    target.close()
    

    It took me awhile moving the parenthesis around and figuring out where to place the formatter and loop, but once I found it, it made perfect sense to me. One key thing to note is that my first attempt:

    for i in range(1, 4):
        lines = raw_input("Line %r :" % i)
    

    Appears to work at first when you run the script, however when you review the target file it only writes the last line (line3) to the file. I'm still not entirely clear on why that is the case.

提交回复
热议问题