非常基本的Python问题(字符串,格式和转义)

Jua*_*oto 6 python string

我开始通过在线指南学习Python,我刚做了一个练习,要求我编写这个脚本:

from sys import argv

script, filename = argv

print "We're going to erase %r." % 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."

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

print "I'm going to write these to the file."

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close()
Run Code Online (Sandbox Code Playgroud)

我让它运行正常,但随后指南说:"这个文件中有太多的重复.使用字符串,格式和转义只用一个target.write()命令打印出line1,line2和line3而不是6 ".

我不知道该怎么做.有人可以帮忙吗?谢谢!

Dav*_*ebb 16

该指南建议创建一个单独的字符串并将其写出来,而不是调用write()六次,这似乎是一个好建议.

你有三个选择.

您可以将字符串连接在一起,如下所示:

line1 + "\n" + line2 + "\n" + line3 + "\n"
Run Code Online (Sandbox Code Playgroud)

或者像这样:

"\n".join(line1,line2,line3) + "\n"
Run Code Online (Sandbox Code Playgroud)

您可以使用旧的字符串格式来执行此操作:

"%s\n%s\n%s\n" % (line1,line2,line3)
Run Code Online (Sandbox Code Playgroud)

最后,您可以使用Python 3中使用的较新的字符串格式,也可以使用Python 2.6:

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

我建议使用最后一种方法,因为当你掌握它时,它是最强大的,它会给你:

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


小智 5

怎么样

target.write('%s \n %s \n %s' % (line1,line2,line3))
Run Code Online (Sandbox Code Playgroud)


Tud*_*tin 1

我认为他们希望你使用字符串连接:

target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
Run Code Online (Sandbox Code Playgroud)

可读性差得多,但你只有一个target.write()命令