Unicode (UTF-8) reading and writing to files in Python

前端 未结 14 1225
谎友^
谎友^ 2020-11-22 17:10

I\'m having some brain failure in understanding reading and writing text to a file (Python 2.4).

# The string, which has an a-acute in it.
ss = u\'Capit\\xe1         


        
14条回答
  •  爱一瞬间的悲伤
    2020-11-22 17:28

    In the notation

    u'Capit\xe1n\n'
    

    the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write

    Capit\xc3\xa1n
    

    into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:

    >>> open('f2').read()
    'Capit\\xc3\\xa1n\n'
    

    You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".

    Edit:

    As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.

    If you actually have a string in this format you can use the string_escape codec to decode it into a normal string:

    In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
    Capitán
    

    The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1 in the original string. If you want to have a unicode string you have to decode again with UTF-8.

    To your edit: you don't have UTF-8 in your file. To actually see how it would look like:

    s = u'Capit\xe1n\n'
    sutf8 = s.encode('UTF-8')
    open('utf-8.out', 'w').write(sutf8)
    

    Compare the content of the file utf-8.out to the content of the file you saved with your editor.

提交回复
热议问题