Python字符串显示
问题描述:
我想要显示什么在line1到line3,它们是来自用户的输入。所以我将它分配给变量print_out
,但不知道如何使它工作,以便当它在文本文件中写入时,它将被缩进为\n
。我应该把什么放在字符串中?Python字符串显示
line1 = raw_input("line 1: ") #input from user and are store in line1
line2 = raw_input("line 2: ") #input from user and are store in line2
line3 = raw_input("line 3: ") #input from user and are store in line3
print_out = #here i want to assign line1-line 3 as string and assign it to variable print_out
txt.write(print_out) #will write whatever it is typed inside print_out on to a file
问题是,我该如何分配东西到print_out
?我知道如何做到这一点,但这是更多的编码,所以我想用字符串来做到这一点。另一种方式是:
txt.write(line1)
txt.write("\n")
txt.write(line2)
txt.write("\n")
txt.write(line3)
txt.write("\n")
但我想用一个字符串来显示这个,所以我不必写太多。我该怎么做,所以它显示像那样,但使用字符串,而不是继续写txt.write输入新行。谢谢。
答
你可以做这样的事情:
print_out = txt.write("{0}\n{1}\n{2}\n".format(line1,line2,line3))
+0
“file.write”的返回值是一个字符串,还是你期望'print_out'是什么? – 2012-02-03 22:53:31
+0
我想通了,但谢谢:) – 2012-02-07 19:45:59
答
print_out = "%s\n" * 3 % (line1, line2, line3)
txt.write(print_out)
从你的帖子,我不能清楚地了解你所要完成的是什么。你可以试试编辑你的问题吗? – 0101amt 2012-02-02 23:41:12
你应该更清楚地表达自己,并使用可用的方式来设置文本的格式,以使其更具可读性。 – 2012-02-03 22:54:06