如何在Python 3中复制Python 2样式的len()?

时间:2019-07-19 15:41:40

标签: python python-3.x

我希望在Python 3中复制Python 2样式len(),因为它与unicode字符串有关。

在Python 2中,unicode字符串的len()是其磁盘上的字节大小。例如:len("애정")返回 6 。在Python 3中,len()返回字符串中的字符数,该示例返回 2

sys.getsizeof()不是解决方案,因为它获取的是Python对象在内存中的大小,而不是对象在写入磁盘后的大小。

1 个答案:

答案 0 :(得分:7)

您可以将其编码为utf8,如下所示。

>>> len('애정'.encode('utf8'))
6
>>>