非常基础的Python问题(字符串、格式和转义)
我正在通过一个在线教程学习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()
我把它运行得很好,但后来教程说:“这个文件里重复的部分太多了。请使用字符串、格式和转义字符,只用一个target.write()命令来打印line1、line2和line3,而不是用6个。”
我不太明白该怎么做。有人能帮忙吗?谢谢!
10 个回答
1
我觉得他们是希望你使用字符串连接:
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
虽然可读性差了点,但你只需要一个 target.write()
命令就可以了。
5
那这样怎么样
target.write('%s \n %s \n %s' % (line1,line2,line3))
16
这个指南建议你把所有内容放在一个字符串里,然后一次性写出来,而不是调用write()
六次,这听起来是个不错的建议。
你有三种选择。
你可以像这样把字符串拼接在一起:
line1 + "\n" + line2 + "\n" + line3 + "\n"
或者这样拼接:
"\n".join(line1,line2,line3) + "\n"
你也可以使用旧的字符串格式化方法来实现:
"%s\n%s\n%s\n" % (line1,line2,line3)
最后,你可以使用在Python 3中引入的更新的字符串格式化,这个方法在Python 2.6及以后版本也可以用:
"{0}\n{1}\n{2}\n".format(line1,line2,line3)
我推荐使用最后一种方法,因为当你掌握了它后,它是最强大的,这样你就可以得到:
target.write("{0}\n{1}\n{2}\n".format(line1,line2,line3))