Programing

파이썬에서 문자열로 유니 코드를 선언하는 이유는 무엇입니까?

crosscheck 2020. 7. 14. 08:25
반응형

파이썬에서 문자열로 유니 코드를 선언하는 이유는 무엇입니까?


나는 여전히 파이썬을 배우고 있으며 의심이 있습니다.

나는 보통 (에로이 같은 파일 헤더에 인코딩 선언한다의 2.6.x 파이썬에서 0263 PEP )

# -*- coding: utf-8 -*-

그 후 내 문자열은 평소와 같이 작성됩니다.

a = "A normal string without declared Unicode"

그러나 파이썬 프로젝트 코드를 볼 때마다 헤더에서 인코딩이 선언되지 않습니다. 대신 다음과 같이 모든 문자열에서 선언됩니다.

a = u"A string with declared Unicode"

차이점이 뭐야? 이것의 목적은 무엇입니까? Python 2.6.x는 기본적으로 ASCII 인코딩을 설정하지만 헤더 선언으로 재정의 할 수 있다는 것을 알고 있습니다. 그래서 문자열 당 선언의 요점은 무엇입니까?

부록 : 파일 인코딩을 문자열 인코딩과 혼합 한 것 같습니다. 설명해 주셔서 감사합니다 :)


이것들은 다른 사람들이 언급했듯이 두 가지 다른 것입니다.

을 지정하면# -*- coding: utf-8 -*- Python에 저장 한 소스 파일이입니다 utf-8. Python 2의 기본값은 ASCII입니다 (Python 3의 경우 utf-8). 이것은 인터프리터가 파일의 문자를 읽는 방법에 영향을 미칩니다.

일반적으로 인코딩에 관계없이 높은 유니 코드 문자를 파일에 포함시키는 것이 가장 좋은 방법은 아닙니다. 인코딩에서 작동하는 문자열 유니 코드 이스케이프를 사용할 수 있습니다.


당신이 가진 문자열을 선언하면 u앞에 같은 u'This is a string', 그것은 문자열이 유니 코드인지 파이썬 컴파일러를 알려줍니다 바이트 없습니다. 이것은 대부분 통역사가 투명하게 처리합니다. 가장 분명한 차이점은 이제 유니 코드 문자를 문자열에 포함시킬 수 있다는 것입니다 (즉, u'\u2665'합법적 임). from __future__ import unicode_literals기본값으로 사용할 수 있습니다 .

이것은 Python 2에만 적용됩니다. Python 3에서 기본값은 유니 코드이며 b앞에 b'These are bytes'바이트를 선언하려면 (와 같이) 을 지정해야합니다 .


다른 사람들이 말했듯 # coding:이 소스 파일이 저장된 인코딩을 지정합니다. 다음은이를 설명하는 몇 가지 예입니다.

디스크에 cp437 (내 콘솔 인코딩)로 저장되었지만 인코딩이 선언되지 않은 파일

b = 'über'
u = u'über'
print b,repr(b)
print u,repr(u)

산출:

  File "C:\ex.py", line 1
SyntaxError: Non-ASCII character '\x81' in file C:\ex.py on line 1, but no
encoding declared; see http://www.python.org/peps/pep-0263.html for details

# coding: cp437추가 된 파일의 출력 :

über '\x81ber'
über u'\xfcber'

처음에 파이썬은 인코딩을 몰랐고 비 ASCII 문자에 대해 불평했습니다. 인코딩을 알면 바이트 문자열은 실제로 디스크에 있던 바이트를 얻습니다. 유니 코드 문자열의 경우, 파이썬은 \ x81을 읽고 cp437에서 이것이 ü 임을 알고 이를 U + 00FC 인 ü 의 유니 코드 코드 포인트로 디코딩했습니다 . 바이트 문자열이 인쇄되면 파이썬은 16 진수 값 81을 콘솔에 직접 보냈습니다 . 유니 코드 문자열이 인쇄 될 때, 파이썬은 제대로 CP437로 내 콘솔 인코딩을 감지 유니 코드 변환 ü를 위한 CP437 값 ü .

UTF-8로 선언되고 저장된 파일은 다음과 같습니다.

├╝ber '\xc3\xbcber'
über u'\xfcber'

In UTF-8, ü is encoded as the hex bytes C3 BC, so the byte string contains those bytes, but the Unicode string is identical to the first example. Python read the two bytes and decoded it correctly. Python printed the byte string incorrectly, because it sent the two UTF-8 bytes representing ü directly to my cp437 console.

Here the file is declared cp437, but saved in UTF-8:

├╝ber '\xc3\xbcber'
├╝ber u'\u251c\u255dber'

The byte string still got the bytes on disk (UTF-8 hex bytes C3 BC), but interpreted them as two cp437 characters instead of a single UTF-8-encoded character. Those two characters where translated to Unicode code points, and everything prints incorrectly.


That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.


The header definition is to define the encoding of the code itself, not the resulting strings at runtime.

putting a non-ascii character like ۲ in the python script without the utf-8 header definition will throw a warning

error


I made the following module called unicoder to be able to do the transformation on variables:

import sys
import os

def ustr(string):

    string = 'u"%s"'%string

    with open('_unicoder.py', 'w') as script:

        script.write('# -*- coding: utf-8 -*-\n')
        script.write('_ustr = %s'%string)

    import _unicoder
    value = _unicoder._ustr

    del _unicoder
    del sys.modules['_unicoder']

    os.system('del _unicoder.py')
    os.system('del _unicoder.pyc')

    return value

Then in your program you could do the following:

# -*- coding: utf-8 -*-

from unicoder import ustr

txt = 'Hello, Unicode World'
txt = ustr(txt)

print type(txt) # <type 'unicode'>

참고URL : https://stackoverflow.com/questions/3170211/why-declare-unicode-by-string-in-python

반응형