如何确定Python中utf-8编码字符串的字节长度? [英] How can I determine the byte length of a utf-8 encoded string in Python?

查看:608
本文介绍了如何确定Python中utf-8编码字符串的字节长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Amazon S3上传,并且键名过长遇到麻烦. S3通过字节而不是字符来限制密钥的长度.

I am working with Amazon S3 uploads and am having trouble with key names being too long. S3 limits the length of the key by bytes, not characters.

从文档中

键的名称是一系列Unicode字符,其UTF-8编码最长为1024个字节.

The name for a key is a sequence of Unicode characters whose UTF-8 encoding is at most 1024 bytes long.

我还尝试将元数据嵌入文件名,因此我需要能够使用Python计算字符串的当前字节长度,以确保元数据不会使密钥过长(在这种情况下,使用单独的元数据文件.

I also attempt to embed metadata in the file name, so I need to be able to calculate the current byte length of the string using Python to make sure the metadata does not make the key too long (in which case I would have to use a separate metadata file).

如何确定utf-8编码字符串的字节长度?同样,我对字符长度不感兴趣...而是对用于存储字符串的实际字节长度感兴趣.

How can I determine the byte length of the utf-8 encoded string? Again, I am not interested in the character length... rather the actual byte length used to store the string.

推荐答案

def utf8len(s):
    return len(s.encode('utf-8'))

在Python 2和3中工作正常.

Works fine in Python 2 and 3.

这篇关于如何确定Python中utf-8编码字符串的字节长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆