如何在下一行打印這些語句?我試過\ 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."
)
如何在下一行打印這些語句?我試過\ 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."
)
它的工作與%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
如果您需要k爲某些行清除原始字符串,則應將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
謝謝,那是因爲我認爲打印原始數據(%r)時不能使用/ n,但在下一行打印原始數據的替代方法是什麼? – Richa
也許使用另一個formater:'formatter =「%r \ n%r \ n%r \ n%r」'? – PRMoureu
但這會打印下一行中的所有格式化程序。對於例如: formatter =「%r%r%r%r」 print formatter%(1,2,3,4) print formatter%( 「我有這個東西。」\ n「, 」你可以輸入正確的。\ n」, ‘但它沒有唱歌。\ n’, ‘所以我說晚安。’ ) 下面的字符串聲明需要在下一行 – Richa
你在什麼操作系統上? –
Mac OS,我正在使用文本牧馬人。 – Richa
您已將此標記爲python-3.x,但您的'print'語句表明您使用的是python-2.x。請更正您的問題或重新登錄。謝謝 –