如何在下一行打印这些语句?我试过\ n但是输出显示\ n而不是在下一行打印语句。我希望使用格式化程序。 代码是:
formatter = "%r %r %r %r"
print formatter %(
"I had this thing.\n",
"That you could type up right.\n ",
"But it didn't sing.\n",
"So I said goodnight."
)
答案 0 :(得分:1)
它正在使用%s
或%r
:
formatter = "%s %s %s %s"
print formatter %(
"I had this thing.\n",
"That you could type up right.\n ",
"But it didn't sing.\n",
"So I said goodnight."
)
%r
使用repr
method,而不会形成特殊字符:
print(repr('\ntext'))
>>> '\ntext'
print(str('\ntext'))
>>>
text
如果您需要保留某些行的原始字符串,则应将formater更改为此模式,并在需要时使用r"rawstrings with special characters"+'\n'
添加换行符。
formatter = "{}{}{}{}"
print(formatter.format(
r"C:\n"+'\n',
"That you could type up right.\n",
"But it didn't sing.",
"So I said goodnight."
))
# >>>C:\n
# That you could type up right.
# But it didn't sing.So I said goodnight.
print(formatter.format(
1,2,3,4)
)
# >>> 1234