为了账号安全,请及时绑定邮箱和手机立即绑定

正确缩进Python多行字符串

正确缩进Python多行字符串

海绵宝宝撒 2019-12-07 16:16:36
函数中Python多行字符串的正确缩进是什么?    def method():        string = """line oneline twoline three"""要么    def method():        string = """line one        line two        line three"""或者是其他东西?在第一个示例中,将字符串挂在函数外部看起来有些奇怪。
查看完整描述

3 回答

?
缥缈止盈

TA贡献2041条经验 获得超4个赞

您可能想与 """


def foo():

    string = """line one

             line two

             line three"""

由于换行符和空格包含在字符串本身中,因此您必须对其进行后处理。如果您不想这样做,并且文本很多,则可能需要将其分别存储在文本文件中。如果文本文件不能很好地适合您的应用程序,并且您不想进行后处理,我可能会选择


def foo():

    string = ("this is an "

              "implicitly joined "

              "string")

如果要对多行字符串进行后处理以修剪掉不需要的部分,则应考虑PEP 257中textwrap介绍的对文档字符串进行后处理的模块或技术:


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)


查看完整回答
反对 回复 2019-12-07
?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

该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!


查看完整回答
反对 回复 2019-12-07
  • 3 回答
  • 0 关注
  • 1141 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信