小编nom*_*ype的帖子

在 Python 3 中使用带有字节的 textwrap.dedent()

当我在 Python 中使用三引号多行字符串时,我倾向于使用 textwrap.dedent 来保持代码可读性,并具有良好的缩进:

some_string = textwrap.dedent("""
    First line
    Second line
    ...
    """).strip()
Run Code Online (Sandbox Code Playgroud)

但是,在 Python 3.x 中, textwrap.dedent 似乎不适用于字节字符串。我在为返回长多行字节字符串的方法编写单元测试时遇到了这个问题,例如:

# The function to be tested

def some_function():
    return b'Lorem ipsum dolor sit amet\n  consectetuer adipiscing elit'

# Unit test

import unittest
import textwrap

class SomeTest(unittest.TestCase):
    def test_some_function(self):
        self.assertEqual(some_function(), textwrap.dedent(b"""
            Lorem ipsum dolor sit amet
              consectetuer adipiscing elit
            """).strip())

if __name__ == '__main__':
    unittest.main()
Run Code Online (Sandbox Code Playgroud)

在 Python 2.7.10 中,上述代码工作正常,但在 Python 3.4.3 中失败:

some_string = textwrap.dedent("""
    First line
    Second line
    ...
    """).strip() …
Run Code Online (Sandbox Code Playgroud)

python indentation literals python-3.x python-unicode

5
推荐指数
2
解决办法
1956
查看次数