将 Python 字符串过滤为字节 3 或更少的 utf8 字符 [英] Filter Python String to utf8 character of bytes 3 or less

查看:43
本文介绍了将 Python 字符串过滤为字节 3 或更少的 utf8 字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤 python 3 字符串,以便只保留 3 个字节或更少的 utf8 字符(我正在写入一个 utf8_general_ci 的 SQL 数据库,它只能占用 3 个字节或更少).有没有一种直接的方法可以在 Python 中做到这一点?任何帮助将不胜感激.

I am trying to filter a python 3 string so that only utf8 characters of 3 bytes or less are kept (I am writing to a SQL db that is utf8_general_ci which can take only 3 bytes or less). Is there a straightforward way to do this in Python? Any help would be very appreciated.

推荐答案

感谢 Giacomo Catenazzi.答案是:''.join(c for c in my_string if ord(c) <= 0xffff)

Thank you Giacomo Catenazzi. Answer is: ''.join(c for c in my_string if ord(c) <= 0xffff)

替代答案''.join([_ for _ in my_string if len(_.encode('utf-8')) <=3])以 ''.join(c for c in my_string if ord(c) <= 0xffff) 的一半速度运行.

Alternative answer of ''.join([_ for _ in my_string if len(_.encode('utf-8')) <=3]) runs at half the speed of ''.join(c for c in my_string if ord(c) <= 0xffff) .

这篇关于将 Python 字符串过滤为字节 3 或更少的 utf8 字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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