python 多行字符串缩进_Python多行字符串的正确缩进

函数中Python多行字符串的正确缩进是什么?

def method():

string = """line one

line two

line three"""

要么

def method():

string = """line one

line two

line three"""

或者是其他东西?

在第一个例子中将字符串悬挂在函数外部看起来有点奇怪。

#1楼

还有一些选择。 在启用了pylab的Ipython中,dedent已经在命名空间中。 我查了一下,它来自matplotlib。 或者它可以导入:

from matplotlib.cbook import dedent

在文档中,它声明它比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

"""

在这三个例子中使用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()

#2楼

这取决于您希望文本显示的方式。 如果你想让它全部左对齐,那么要么像在第一个片段中那样对它进行格式化,要么迭代左边的行 - 修剪所有空格。

#3楼

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)

日志消息文字中的尾随\\是为了确保换行符不在文字中; 这样,文字不会以空行开头,而是从下一个完整行开始。

textwrap.dedent的返回值是输入字符串,在字符串的每一行上删除了所有常见的前导空格缩进 。 所以上面的log_message值将是:

Prepare to frobnicate:

Here it comes...

Any moment now.

And: Frobnicate!

#4楼

你可能想要排队"""

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)

#5楼

其他答案中似乎缺少的一个选项(仅在naxa的评论中深入提及)如下:

def foo():

string = ("line one\n" # Add \n in the string

"line two" "\n" # Add "\n" after the string

"line three\n")

这将允许正确对齐,隐含地连接线,并仍然保持线移位,对我来说,这是我想要使用多线字符串的原因之一。

它不需要任何后期处理,但您需要在任何希望该行结束的给定位置手动添加\\n 。 内联或后面的单独字符串。 后者更容易复制粘贴。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值