1. 程式人生 > 實用技巧 >Python encode與decode完美封裝

Python encode與decode完美封裝

需求:字串轉為位元組,位元組轉為字串,這個是網路程式設計最常用的需求
注意:此程式碼來源Tornado原始碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import typing
from typing import Optional, Union

unicode_type = str

_UTF8_TYPES = (bytes, type(None))
@typing.overload
def utf8(value: bytes) -> bytes:
    pass


@typing.overload  # noqa: F811
def
utf8(value: str) -> bytes: pass @typing.overload # noqa: F811 def utf8(value: None) -> None: pass def utf8(value: Union[None, str, bytes], code_type='utf-8') -> Optional[bytes]: # noqa: F811 """ utf-8編碼""" if isinstance(value, _UTF8_TYPES): return value if not
isinstance(value, unicode_type): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.encode(code_type) @typing.overload def to_unicode(value: str) -> str: pass @typing.overload # noqa: F811 def to_unicode(value: bytes) -> str: pass @typing.overload
# noqa: F811 def to_unicode(value: None) -> None: pass _TO_UNICODE_TYPES = (unicode_type, type(None)) def to_unicode(value: Union[None, str, bytes], code_type='utf-8') -> Optional[str]: # noqa: F811 """位元組型別轉為字串""" if isinstance(value, _TO_UNICODE_TYPES): return value if not isinstance(value, bytes): raise TypeError("Expected bytes, unicode, or None; got %r" % type(value)) return value.decode(code_type) if __name__ == '__main__': s = utf8('中國') print('編碼:', s) ret = to_unicode(s) print('解碼:', ret)
執行結果
編碼: b'\xe4\xb8\xad\xe5\x9b\xbd'
解碼: 中國