2017-08-31 41 views
-1

如何在下一行打印这些语句?我试过\ 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

你在什么操作系统上? –

+0

Mac OS,我正在使用文本牧马人。 – Richa

+2

您已将此标记为python-3.x,但您的'print'语句表明您使用的是python-2.x。请更正您的问题或重新登录。谢谢 –

回答

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 

如果您需要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 
+0

谢谢,那是因为我认为打印原始数据(%r)时不能使用/ n,但在下一行打印原始数据的替代方法是什么? – Richa

+0

也许使用另一个formater:'formatter =“%r \ n%r \ n%r \ n%r”'? – PRMoureu

+0

但这会打印下一行中的所有格式化程序。对于例如: formatter =“%r%r%r%r” print formatter%(1,2,3,4) print formatter%( “我有这个东西。”\ n“, ”你可以输入正确的。\ n”, ‘但它没有唱歌。\ n’, ‘所以我说晚安。’ ) 下面的字符串声明需要在下一行 – Richa