函数中Python多行字符串的正确缩进是什么?
def method():
string = """line one
line two
line three"""
Run Code Online (Sandbox Code Playgroud)
要么
def method():
string = """line one
line two
line three"""
Run Code Online (Sandbox Code Playgroud)
或者是其他东西?
在第一个例子中将字符串悬挂在函数外部看起来有点奇怪.
Mik*_*ham 439
你可能想要排队 """
def foo():
string = """line one
line two
line three"""
Run Code Online (Sandbox Code Playgroud)
由于换行符和空格都包含在字符串本身中,因此您必须对其进行后处理.如果您不想这样做并且您有大量文本,则可能需要将其单独存储在文本文件中.如果文本文件不适合您的应用程序,并且您不想进行后期处理,我可能会选择
def foo():
string = ("this is an "
"implicitly joined "
"string")
Run Code Online (Sandbox Code Playgroud)
如果要对多行字符串进行后处理以修剪掉不需要的部分,则应考虑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)
Run Code Online (Sandbox Code Playgroud)
big*_*ose 239
该textwrap.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)
Run Code Online (Sandbox Code Playgroud)
\日志消息文字中的尾随是为了确保换行符不在文字中; 这样,文字不会以空行开头,而是从下一个完整行开始.
返回值textwrap.dedent是输入字符串,在字符串的每一行上删除了所有常见的前导空格缩进.所以上面的log_message值将是:
Prepare to frobnicate:
Here it comes...
Any moment now.
And: Frobnicate!
Run Code Online (Sandbox Code Playgroud)
wih*_*lke 32
使用inspect.cleandoc如下:
def method():
string = inspect.cleandoc("""
line one
line two
line three""")
Run Code Online (Sandbox Code Playgroud)
相对缩进将按预期保持.
注意:最好在其相关上下文中缩进代码的逻辑块以阐明结构.例如,属于变量的多行字符串
textwrap.dedent.
hol*_*roy 22
其他答案中似乎缺少的一个选项(仅在naxa的评论中深入提及)如下:
def foo():
string = ("line one\n" # Add \n in the string
"line two" "\n" # Add "\n" after the string
"line three\n")
Run Code Online (Sandbox Code Playgroud)
这将允许正确对齐,隐含地连接线,并仍然保持线移位,对我来说,这是我想要使用多线字符串的原因之一.
它不需要任何后期处理,但您需要\n在任何给定位置手动添加您希望该行结束的位置.内联或后面的单独字符串.后者更容易复制粘贴.
Joo*_*oop 17
还有一些选择.在启用了pylab的Ipython中,dedent已经在命名空间中.我查了一下,它来自matplotlib.或者它可以导入:
from matplotlib.cbook import dedent
Run Code Online (Sandbox Code Playgroud)
在文档中它声明它比textwrap等效的快,并且在我的ipython测试中,它的平均速度确实比我的快速测试快3倍.它还有一个好处,它丢弃任何前导空行,这使您可以灵活地构建字符串:
"""
line 1 of string
line 2 of string
"""
"""\
line 1 of string
line 2 of string
"""
"""line 1 of string
line 2 of string
"""
Run Code Online (Sandbox Code Playgroud)
在这三个例子中使用matplotlib dedent将给出相同的合理结果.textwrap dedent函数将在第一个示例中有一个前导空白行.
显而易见的缺点是textwrap在标准库中,而matplotlib是外部模块.
这里有一些权衡... dedent函数使得代码在字符串定义时更具可读性,但稍后需要处理才能使字符串成为可用格式.在文档字符串中,显然您应该使用正确的缩进,因为docstring的大多数用法都将执行所需的处理.
当我在我的代码中需要一个非长字符串时,我发现以下公认的丑陋代码,其中我让长字符串从封闭缩进中删除.绝对失败的是"美丽胜过丑陋."但是有人可能会认为它比狡猾的选择更简单,更明确.
def example():
long_string = '''\
Lorem ipsum dolor sit amet, consectetur adipisicing
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.\
'''
return long_string
print example()
Run Code Online (Sandbox Code Playgroud)
如果您想要一个快速简便的解决方案并且不用输入换行符,您可以选择列表,例如:
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
Run Code Online (Sandbox Code Playgroud)
我更喜欢
def method():
string = \
"""\
line one
line two
line three\
"""
Run Code Online (Sandbox Code Playgroud)
或者
def method():
string = """\
line one
line two
line three\
"""
Run Code Online (Sandbox Code Playgroud)