开发者

How to convert from unicode with python

In database I have saved string in which the problem word is: za\u0161\u010diten.

[ed.: the "problem word" seems to have changed]

When I want to present this string on my page (with req.write(string)). I get this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 686-687: ordinal not in range(128).

I am using Python 2.X on Windows|linux|Mac. [ed.: select one]

My string is actually named html_h2. Here are the details I was asked for: [ed.: whitespace inserted for legibility]

>> print type(html_h2)
<type 'unicode'>
>> print repr(html_h2)
u"\n<table bgcolor='white' border=1 cellpadding=2 cellspacing=1 rules=rows frame=box>
  <tr>
    <td align='center'>
      <img src=img/_up/upload/2010/03/03/… width=120 height=100/>
    </td>
    <td align='left' style=width:86%>
      <h3>V Gr\u010diji kot v vojni</h3>
      Gr\u0161ki premier je finan\u010dne razmere v dr\u017eavi, ki je 开发者_开发问答skoraj pred bankrotom, primerjal z razmerami v vojni. Napovedani so ostri var\u010devalni ukrepi.
    </td>
  </tr>
</table>"

I insert database fields in string with %s. [ed.: irrelevant]

When I do as Ignacio suggested:

req.write(html_h2.encode('XXXXXX'))

where XXXXXX is the charset I declared in the Content-Type header, this happens:

[ed.: delete the outcome that doesn't happen]

(1) It displays just like I'd hoped for.

(2) I get an error message: XXXXXXXXXXXXXXXXXXXXXXXXXX


req.write(string.encode(encoding))

where encoding is the charset you declared in the Content-Type header.


If string refers to the string module, then yes that string doesn't have encode. If string is in fact a unicode object, then it does have an encode but perhaps string may in fact be an str object.

Back to basics: please give us some information.

Please show the results of:

# Python 2.X
print type(string)
print repr(string)

or

# Python 3.X
print(type(string))
print(ascii(string))

Then we can give you informed advice rather than uninformed guesses.

Note: please edit your question to show the output, don't respond in a comment. Use copy/paste, don't type from memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜