代码之家  ›  专栏  ›  技术社区  ›  systempuntoout

如何使用Python获得UTF-8字符串的字节大小

  •  8
  • systempuntoout  · 技术社区  · 14 年前

    有这样一个UTF-8字符串:

    mystring = "işğüı"
    

    用Python(2.5)可以得到它(内存中)的字节大小吗?

    1 回复  |  直到 14 年前
        1
  •  7
  •   Josh Lee ZZ Coder    14 年前

    假设您的意思是UTF-8字节的数量(而不是Python存储对象所需的额外字节),这与任何其他字符串的长度相同。python2.x中的字符串文本是编码字节的字符串,而不是Unicode字符。

    字节字符串:

    >>> mystring = "işğüı"
    >>> print "length of {0} is {1}".format(repr(mystring), len(mystring))
    length of 'i\xc5\x9f\xc4\x9f\xc3\xbc\xc4\xb1' is 9
    

    >>> myunicode = u"işğüı"
    >>> print "length of {0} is {1}".format(repr(myunicode), len(myunicode))
    length of u'i\u015f\u011f\xfc\u0131' is 5
    

    最好的做法是用Unicode维护所有字符串,并且只在与外部世界通信时进行编码。在这种情况下,您可以使用 len(myunicode.encode('utf-8')) 找到编码后的大小。