函数中Python多行字符串的缩进方式是怎样的?
def method():
string = """line one
line two
line three"""
or
def method():
string = """line one
line two
line three"""
还是别的什么?
在第一个例子中,将字符串挂在函数外面看起来有点奇怪。
函数中Python多行字符串的缩进方式是怎样的?
def method():
string = """line one
line two
line three"""
or
def method():
string = """line one
line two
line three"""
还是别的什么?
在第一个例子中,将字符串挂在函数外面看起来有点奇怪。
当前回答
如果你想要一个快速简单的解决方案,并且避免输入换行符,你可以选择一个列表来代替,例如:
def func(*args, **kwargs):
string = '\n'.join([
'first line of very long string and',
'second line of the same long thing and',
'third line of ...',
'and so on...',
])
print(string)
return
其他回答
我的观点是,转义行尾以获得缩进
def foo():
return "{}\n"\
"freq: {}\n"\
"temp: {}\n".format( time, freq, temp )
我来这里寻找一个简单的1-liner来删除/纠正打印文档字符串的标识级别,而不会使它看起来不整洁,例如通过使它在脚本中“悬挂在函数之外”。
这是我最后做的:
import string
def myfunction():
"""
line 1 of docstring
line 2 of docstring
line 3 of docstring"""
print str(string.replace(myfunction.__doc__,'\n\t','\n'))[1:]
显然,如果你使用空格缩进(例如4)而不是制表键,可以使用这样的方法:
print str(string.replace(myfunction.__doc__,'\n ','\n'))[1:]
如果你想让你的文档字符串看起来像这样,你不需要删除第一个字符:
"""line 1 of docstring
line 2 of docstring
line 3 of docstring"""
print string.replace(myfunction.__doc__,'\n\t','\n')
这取决于您希望文本如何显示。如果你想让它全部向左对齐,那么要么像第一个代码片段那样格式化它,要么遍历所有的行,向左修剪所有的空间。
我更喜欢
def method():
string = \
"""\
line one
line two
line three\
"""
or
def method():
string = """\
line one
line two
line three\
"""
dedent函数允许在源代码中以正确的缩进开始,然后在使用之前将其从文本中剥离。
正如其他人所指出的那样,这是对字面量的额外函数调用;在决定在代码中放置这些文字的位置时,要考虑到这一点。
import textwrap
def frobnicate(param):
""" Frobnicate the scrognate param.
The Weebly-Ruckford algorithm is employed to frobnicate
the scrognate to within an inch of its life.
"""
prepare_the_comfy_chair(param)
log_message = textwrap.dedent("""\
Prepare to frobnicate:
Here it comes...
Any moment now.
And: Frobnicate!""")
weebly(param, log_message)
ruckford(param)
日志消息字面量中尾随的\是为了确保换行符不在字面量中;这样,字面量就不会以空行开始,而是以下一行开始。
dedent的返回值是删除了字符串每行上所有常用前导空格缩进的输入字符串。所以上面的log_message值将是:
Prepare to frobnicate:
Here it comes...
Any moment now.
And: Frobnicate!