函数中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
其他回答
第一个选项是好的-包括缩进。 它是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
使用检查。Cleandoc像这样:
import inspect
def method():
string = inspect.cleandoc("""
line one
line two
line three""")
相对压痕将按预期保持。正如下面所评论的,如果你想保持前面的空行,使用textwrap.dedent。但是,这也保留了第一个换行符。
注意:在相关上下文下缩进代码逻辑块以澄清结构是一种良好的实践。例如,多行字符串属于变量字符串。
一个选项似乎在其他答案中遗漏了(只在naxa的评论中提到过):
def foo():
string = ("line one\n" # Add \n in the string
"line two" "\n" # Add "\n" after the string
"line three\n")
这将允许适当的对齐,隐式地连接行,并仍然保持行移位,对我来说,这是为什么我想使用多行字符串的原因之一。
它不需要任何后处理,但您需要手动在希望该行结束的任何给定位置添加\n。可以内联,也可以作为单独的字符串。后者更容易复制粘贴进来。