How to handle multibyte string in Python
Asked Answered
B

2

5

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

Is there any package or function like mb_strlen in PHP?

Burgle answered 1/12, 2011 at 18:46 Comment(1)
For the completeness: This is no longer a problem in Python 3 with native Unicode support on all strings.Carney
O
9

Use Unicode strings:

# Encoding: UTF-8

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

Note the u in front of the string.

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

Overblouse answered 1/12, 2011 at 18:50 Comment(0)
O
3

Try converting it to unicode first:

print len(japanese.decode("utf-8"))

gives 7. You are working on the utf-8 encoded string, which indeed has 21 bytes.

Osber answered 1/12, 2011 at 18:50 Comment(2)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128) :(Burgle
To remove the error:<br/> UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128) :( <br/> Add the following hashed line:<br/> # Encoding: UTF-8<br/>Duchess

© 2022 - 2024 — McMap. All rights reserved.