函数中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 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 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():
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)
对于字符串,可以直接处理字符串。对于文档字符串,您需要在之后处理函数。这里有一个解决方案,这两个仍然是可读的。
class Lstrip(object):
def __rsub__(self, other):
import re
return re.sub('^\n', '', re.sub('\n$', '', re.sub('\n\s+', '\n', other)))
msg = '''
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
''' - Lstrip()
print msg
def lstrip_docstring(func):
func.__doc__ = func.__doc__ - Lstrip()
return func
@lstrip_docstring
def foo():
'''
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
'''
pass
print foo.__doc__
第一个选项是好的-包括缩进。 它是python风格的-提供了代码的可读性。
正确显示:
print string.lstrip()
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!