4

我有以下代码:

print "my name is [%s], I like [%s] and I ask question on [%s]" % ("xxx", "python", "stackoverflow")

我想将此 LONG 行拆分为多行:

print
  "my name is [%s]"
  ", I like [%s] "
  "and I ask question on [%s]"
  % ("xxx", "python", "stackoverflow")

你能提供正确的语法吗?

4

3 回答 3

11

通过将所有内容放在括号内来使用隐含的行继续。这是Python 的样式指南 (PEP 8)中推荐的方法:

print ("my name is [%s]"
       ", I like [%s] "
       "and I ask question on [%s]"
       % ("xxx", "python", "stackoverflow"))

这是有效的,因为 Python 解释器将连接相邻的字符串文字,因此"foo" 'bar'变成'foobar'.

于 2013-06-12T22:53:50.170 回答
1

另一种风格:

print "my name is [%s], I like [%s] and I ask question on [%s]" % (
    "xxx", "python", "stackoverflow")
于 2013-06-13T00:57:42.660 回答
0
str_val = '''"my name is [%s]"
  ", I like [%s] "
  "and I ask question on [%s]"
  % ("xxx", "python", "stackoverflow")'''

print(str_val)
于 2020-07-29T18:07:27.027 回答