Python: 유니코드로 이스케이프된 문자열에서 .format() 사용
나는 Python 2.6.5를 사용하고 있다.내 코드는 "이상 또는 이하" 기호를 사용해야 한다.자, 시작한다:
>>> s = u'\u2265'
>>> print s
>>> ≥
>>> print "{0}".format(s)
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265'
in position 0: ordinal not in range(128)`
이 오류가 발생하는 이유이것을 하는 올바른 방법이 있을까?I need to use the world.format()
기능을 하다
두 번째 문자열도 유니코드 문자열로 만드십시오.
>>> s = u'\u2265'
>>> print s
≥
>>> print "{0}".format(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265' in position 0: ordinal not in range(128)
>>> print u"{0}".format(s)
≥
>>>
unicode
필요unicode
현을 치다
>>> print u'{0}'.format(s)
≥
왜 그런 일이 생기는지 좀 더 자세한 정보.
>>> s = u'\u2265'
>>> print s
때문에 효과가 있다.print
UTF-8로 설정되었을 가능성이 높은 사용자 환경에 대해 시스템 인코딩을 자동으로 사용한다.(확인하려면import sys; print sys.stdout.encoding
)
>>> print "{0}".format(s)
때문에 실패하다format
호출되는 유형의 인코딩을 일치시키려 함(이 항목에 대한 문서를 찾을 수 없었지만, 이것이 내가 알아차린 행동이다).문자열 리터럴은 파이선 2에서 ASCII로 인코딩된 바이트 문자열이기 때문에,format
암호화를 시도하다s
ASCII로, 그러면 그 예외로 된다.다음을 관찰하십시오.
>>> s = u'\u2265'
>>> s.encode('ascii')
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265' in position 0: ordinal not in range(128)
그래서 기본적으로 이러한 접근법이 효과가 있는 것이다.
>>> s = u'\u2265'
>>> print u'{}'.format(s)
≥
>>> print '{}'.format(s.encode('utf-8'))
≥
원본 문자 집합은 인코딩 선언에 의해 정의되며, 원본 파일에 인코딩 선언이 없는 경우 ASCII이다(https://docs.python.org/2/reference/lexical_analysis.html#string-literals)
참조URL: https://stackoverflow.com/questions/3235386/python-using-format-on-a-unicode-escaped-string
'programing' 카테고리의 다른 글
RxJS6 asObservable()이 주제에 필요한가? (0) | 2022.04.09 |
---|---|
vue 2 라우터에 html "partial" 템플릿(js에 포함되지 않음)을 포함할 수 있는가? (0) | 2022.04.09 |
인덱스로 라우터 리디렉션 응답 (0) | 2022.04.09 |
rxjs 관찰 가능 .map 실행되지 않음 (0) | 2022.04.09 |
각도 2: 값이 변경된 후 FormControl 검증기 업데이트 (0) | 2022.04.09 |