Python 多行字符串的正确缩进 [英] Proper indentation for Python multiline strings

查看:77
本文介绍了Python 多行字符串的正确缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the proper indentation for Python multiline strings within a function?

    def method():
        string = """line one
line two
line three"""

    def method():
        string = """line one
        line two
        line three"""

还是别的?

在第一个示例中将字符串挂在函数外看起​​来有点奇怪.

It looks kind of weird to have the string hanging outside the function in the first example.

推荐答案

你可能想与"""

def foo():
    string = """line one
             line two
             line three"""

由于换行符和空格包含在字符串本身中,因此您必须对其进行后处理.如果您不想这样做并且您有大量文本,您可能希望将其单独存储在一个文本文件中.如果文本文件不适用于您的应用程序并且您不想进行后处理,我可能会选择

Since the newlines and spaces are included in the string itself, you will have to postprocess it. If you don't want to do that and you have a whole lot of text, you might want to store it separately in a text file. If a text file does not work well for your application and you don't want to postprocess, I'd probably go with

def foo():
    string = ("this is an "
              "implicitly joined "
              "string")

如果您想对多行字符串进行后处理以修剪掉不需要的部分,您应该考虑 textwrap 模块或 PEP 257:

If you want to postprocess a multiline string to trim out the parts you don't need, you should consider the textwrap module or the technique for postprocessing docstrings presented in 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)

这篇关于Python 多行字符串的正确缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆