当我使用Python中的三引号多行字符串,我倾向于使用textwrap.dedent保持代码的可读性,具有良好的缩进:使用Python中与字节textwrap.dedent()3
some_string = textwrap.dedent("""
First line
Second line
...
""").strip()
但是,在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()
在Python 2.7.10上面的代码工作正常,但在Python 3.4.3失败:
E
======================================================================
ERROR: test_some_function (__main__.SomeTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test.py", line 16, in test_some_function
""").strip())
File "/usr/lib64/python3.4/textwrap.py", line 416, in dedent
text = _whitespace_only_re.sub('', text)
TypeError: can't use a string pattern on a bytes-like object
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
因此:是否有替代textwrap.dedent与字节字符串?
- 我可以自己编写这样一个函数,但是如果有一个现有函数,我宁愿使用它。
- 我可以转换为unicode,使用textwrap.dedent,并转换回字节。但是,如果字节字符串符合一些Unicode编码,这是唯一可行的。
使用hex.b以外的好主意。我已经在我的项目中使用了六个,所以使用six.b不会增加额外的依赖。我的编码担忧并不是关于源文件中的非ASCII字符,而是像“\ xff”这样的十六进制转义序列。不过,我现在已经测试,它适用于所有这些序列(six.b(S)上的Python 3等同于s.encode(“拉丁-1”))。我会接受这个答案。 – nomadictype