为什么target.write忽略我的%r格式?

0 python format python-2.6 operator-keyword

我正在尝试编写一个类似于这个人的程序,该程序靠近页面顶部的Learn Python the Hard Way程序.

http://learnpythonthehardway.org/book/ex16.html

这是我的下面版本.但它告诉我"%r"最后使用它为什么这样做?我认为这就是你在括号中要做的事情.

# -- coding: utf-8 --

from sys import argv

script, filename = argv

print "Would you like file %r to be overwritten?" % filename
print "Press RETURN if you do, and CTRL-C otherwise."

raw_input('> ')

print "Opening the file ..."
target = open(filename, 'w')
target.truncate()

print "Now type three lines to replace the contents of %r" % filename

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "The lines below have now overwritten the previous contests."

target.write("%r\n%r\n%r") % (line1, line2, line3)
target.close()
Run Code Online (Sandbox Code Playgroud)

iCo*_*dez 5

您需要将%操作符直接放在格式字符串之后.在这里取括号:

target.write("%r\n%r\n%r") % (line1, line2, line3)
#                      --^
Run Code Online (Sandbox Code Playgroud)

并将其移至行尾:

target.write("%r\n%r\n%r" % (line1, line2, line3))
#                                              --^
Run Code Online (Sandbox Code Playgroud)

另外,我想提一下,现在执行字符串格式化操作%是不满意的.现代方法是使用str.format:

target.write("{0!r}\n{1!r}\n{2!r}".format(line1, line2, line3))
Run Code Online (Sandbox Code Playgroud)