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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值