函数中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"""
还是别的什么?
在第一个例子中,将字符串挂在函数外面看起来有点奇怪。
当前回答
一个选项似乎在其他答案中遗漏了(只在naxa的评论中提到过):
def foo():
string = ("line one\n" # Add \n in the string
"line two" "\n" # Add "\n" after the string
"line three\n")
这将允许适当的对齐,隐式地连接行,并仍然保持行移位,对我来说,这是为什么我想使用多行字符串的原因之一。
它不需要任何后处理,但您需要手动在希望该行结束的任何给定位置添加\n。可以内联,也可以作为单独的字符串。后者更容易复制粘贴进来。
其他回答
第一个选项是好的-包括缩进。 它是python风格的-提供了代码的可读性。
正确显示:
print string.lstrip()
如果你想要一个快速简单的解决方案,并且避免输入换行符,你可以选择一个列表来代替,例如:
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
我来这里寻找一个简单的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 foo():
string = """line one
line two
line three"""
由于换行符和空格包含在字符串本身中,因此必须对其进行后处理。如果你不想这样做,而你有很多文本,你可能想把它们单独存储在一个文本文件中。如果一个文本文件不适合你的应用程序,而你不想进行后期处理,我可能会选择
def foo():
string = ("this is an "
"implicitly joined "
"string")
如果你想对一个多行字符串进行后处理,去掉你不需要的部分,你应该考虑textwrap模块或PEP 257中提供的后处理文档字符串的技术:
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
我的观点是,转义行尾以获得缩进
def foo():
return "{}\n"\
"freq: {}\n"\
"temp: {}\n".format( time, freq, temp )