Python多行字符串如何避免把缩进也当成字符串的内容

def print_multiline():
    """print multiline string to test dedent and cleandoc"""
    
    multiline_string = """This is the first line.
    This is the second line with proper indentation.
    This is the third line."""
    
    print(multiline_string)


print_multiline()

输出:

This is the first line.
    This is the second line with proper indentation.
    This is the third line.

多行字符串会将每一行的缩进也当成该行的内容,虽然可以通过删除缩进来避免这个问题,但是看起来会很奇怪:

def print_multiline():
    """print multiline string to test dedent and cleandoc"""
    
    multiline_string = """This is the first line.
This is the second line with proper indentation.
This is the third line."""

    print(multiline_string)

解决方法有两个:textwrap.dedent和inspect.cleandoc

from textwrap import dedent


def print_multiline():
    """print multiline string to test dedent and cleandoc"""

    multiline_string = """    This is the first line.
    This is the second line with proper indentation.
    This is the third line."""

    print(dedent(multiline_string))


print_multiline()

输出:

This is the first line.
This is the second line with proper indentation.
This is the third line.

需要注意的一点是dedent()是按缩进最少的行来对齐的,意味着如果希望最终结果是缩进一致的,那么原始字符串的缩进就应该一致(因此可以看到在上面的例子找那个为第一行也加上了相同的缩进)。dedent()默认只处理空格字符,而不处理制表符(tab)字符。

inspect.cleandoc()比dedent()更强大的地方在于对于第一行不要求同样的缩进。

from inspect import cleandoc

def print_multiline():
    """print multiline string to test dedent and cleandoc"""

    multiline_string = """This is the first line.
    This is the second line with proper indentation.
    This is the third line."""

    print(cleandoc(multiline_string))


print_multiline()

输出:

This is the first line.
This is the second line with proper indentation.
This is the third line.

你可能感兴趣的:(Python,python,开发语言)