How are these strings represented internally in Python interpreter ? I don't understand

后端 未结 1 1811
攒了一身酷
攒了一身酷 2021-01-13 09:52
# -*- coding: utf-8 -*-

a = \'éáűőúöüó€\'
print type(a)    # 
print a          # éáűőúöüó€
print ord(a[-1]) # 172

Why is this

相关标签:
1条回答
  • 2021-01-13 10:53

    There are unicode literals in the string

    No, there are not. There are bytes in the string. Python simply goes with the bytes your editor saved to disk when you created the file.

    When you prefixed the string with a u'', you signalled to python that you are creating a unicode object instead. Python now pays attention to the encoding you specified at the top of your source file, and it decodes the bytes in the source file to a unicode object based on the encoding you specified.

    In both cases, your editor saved a series of bytes to a file, for the character, the UTF-8 encoding is three bytes, represented in hexadecimal as E282AC. The last byte in the bytestring is thus AC, or 172 in decimal. Once you decode the last 3 bytes as UTF-8, they together become the Unicode codepoint U+20AC, which is 8364 in decimal.

    You really should read up on Python and Unicode:

    • The Python Unicode HOWTO

    • Pragmatic Unicode by Ned Batchelder

    • The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky

    0 讨论(0)
提交回复
热议问题