如何在Python中处理多字节字符串 [英] How to handle multibyte string in Python

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

问题描述

PHP中有多字节字符串函数来处理多字节字符串(例如CJK脚本).例如,我想通过使用python中的len函数来计算一个多字节字符串中有多少个字母,但是它返回的结果不准确(即该字符串中的字节数)

There are multibyte string functions in PHP to handle multibyte string (e.g:CJK script). For example, I want to count how many letters in a multi bytes string by using len function in python, but it return an inaccurate result (i.e number of bytes in this string)

japanese = "桜の花びらたち"
print japanese
print len(japanese)#return 21 instead of 7

在PHP中是否有像mb_strlen这样的包或函数?

Is there any package or function like mb_strlen in PHP?

推荐答案

使用 Unicode字符串 :

# Encoding: UTF-8

japanese = u"桜の花びらたち"
print japanese
print len(japanese)

请注意字符串前面的u.

要将字节字符串转换为Unicode,请使用decode:"桜の花びらたち".decode('utf-8')

To convert a bytestring into Unicode, use decode: "桜の花びらたち".decode('utf-8')

这篇关于如何在Python中处理多字节字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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