tags:

views:

154

answers:

3
print str.decode
print unicode.encode

thanks

A: 
print 'あ'.decode('utf-8')
print repr(u'あ'.encode('shift-jis'))
Ignacio Vazquez-Abrams
File "D:\zjm_code\a.py", line 4SyntaxError: Non-ASCII character '\xe3' in file D:\zjm_code\a.py on line 4, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
zjm1126
Read that URL and fix your source.
Ignacio Vazquez-Abrams
@zjm1126: insert as first line: `# coding: utf-8`
John Machin
Traceback (most recent call last): File "D:\zjm_code\a.py", line 5, in <module> print '\xe3\x81\x82'.decode('utf-8')UnicodeEncodeError: 'ascii' codec can't encode character u'\u3042' in position 0: ordinal not in range(128)
zjm1126
@zjm1126: as you have been advised previously, use print repr(some_unicode) instead of print some_unicode ... Windows stdout just doesn't grok unicode
John Machin
+1  A: 

Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the same thing with only safe string escapes (reprs):

>>> '\xe3\x81\x82'.decode('utf-8')    # three top-bit-set bytes, representing one character
u'\u3042'                             # Hiragana letter A

>>> u'\u3042'.encode('shift-jis')
'\x82\xa0'                            # only requires two bytes in the Shift-JIS encoding

>>> unicode('\x82\xa0', 'shift-jis')  # alternative way of doing a decode
u'\u3042'

when you're writing to eg. a file or via a web server, or you're on another operating system where the console supports UTF-8, it's a bit easier.

bobince
A: 
>>> unicode.encode(u"abcd","utf8")
'abcd' #unicode string u"abcd" got encoded to UTF-8 encoded string "abcd"

>>> str.decode("abcd","utf8")
u'abcd' #UTF-8 string "abcd" got decoded to python's unicode object u"abcd"
>>>
S.Mark
There is no reason to be calling these on the class when they can just as (if not more) easily be called on an instance.
Ignacio Vazquez-Abrams
Yes, right, I just want to show OP's example as is.
S.Mark