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)
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)
Note: It's good practice to indent logical blocks of code under its related context to clarify the structure. E.g. the multi-line string belonging to the variable string.
^{} 函数允许从源代码中的正确缩进开始,然后在使用前将其从文本中删除。
正如其他一些人所指出的,权衡的结果是,这是对文本的额外函数调用;在决定将这些文本放在代码中的位置时,要考虑到这一点。
日志消息文本中的尾部
\
是为了确保换行符不在文本中;这样,文本就不会以空行开头,而是以下一整行开头。来自
textwrap.dedent
的返回值是输入字符串,该字符串的每一行上都删除了所有公共前导空白缩进。所以上面的log_message
值将是:你可能想和
"""
排队由于换行符和空格包含在字符串本身中,因此必须对其进行后处理。如果您不想这样做,而且您有大量的文本,您可能希望将其单独存储在一个文本文件中。如果一个文本文件不适合你的应用程序并且你不想进行后处理,我可能会
如果要对多行字符串进行后处理以删除不需要的部分,则应考虑^{} 模块或PEP 257中提供的后处理docstring的技术:
像这样使用^{} :
将按预期保持相对缩进。如下面的commented所示,如果要保留前面的空行,请使用^{} 。然而,这也保持了第一行中断。
相关问题 更多 >
编程相关推荐