kkkkkk
kkkkkk

Reputation: 692

How to use string.translate() to translate this?

first, I have this:

strSrc = '3.14'

And I hope the result is this:

strRst = '叁点壹肆'

P.s: The number '3' in traditional-Chinese is '叁'. Here:

0零 1壹 2贰 3叁 4肆 5伍 6陆 7柒 8捌 9玖

I want to translate strSrc into Chinese using string.translate().

I check the string.translate() doc,it said:

and then translate the characters using table, which must be a 256-character string

so, does that mean I should NOT use string.translate() to solve this problem??


but it always occurs encode problem, like this:

>>> engToChn = string.maketrans('0123456789.', '零壹贰叁肆伍陆柒捌玖点')
Traceback (most recent call last):
    File "<stdin>", line 1, in <module> 
ValueError: maketrans arguments must have same length

if you try this:

>>> engToChn = string.maketrans('0123456789.', u'零壹贰叁肆伍陆柒捌玖点')
or
>>> engToChn = string.maketrans(u'0123456789.', u'零壹贰叁肆伍陆柒捌玖点')

it will this problem:

Traceback (most recent call last)
    File "<stdin>", line 1, in module
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10: ordinal not in range(128)

Upvotes: 1

Views: 558

Answers (1)

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

The problem is that Hanzi (chinese characters) don't fit into strings.

Try the following:

transtable = { ord("0"):u'零', ord("1"):u'壹', ....}
unicodestr = u"314"
print unicodestr.translate(transtable)

Upvotes: 1

Related Questions