簡體   English   中英

如何在python 3中使用raw_unicode_escape編碼打印字符串?

[英]How can you print a string using raw_unicode_escape encoding in python 3?

以下在帶有TypeError: must be str, not bytes Python 3.x中失敗的代碼TypeError: must be str, not bytes因為現在encode()返回bytesprint()僅期望str

#!/usr/bin/python
from __future__ import print_function
str2 = "some unicode text"
print(str2.encode('raw_unicode_escape'))

如何使用print()打印Unicode字符串轉義的表示形式? 我正在尋找一種適用於Python 2.6或更高版本(包括3.x)的解決方案

更新

下面的行適用於3.x,但不適用於2.6,生成AttributeError: 'file' object has no attribute 'buffer'

sys.stdout.buffer.write(str2.encode('raw_unicode_escape'))

我只用:

print(str2.encode('raw_unicode_escape').decode('ascii'))

如果要在Python 3和Python 2.6中使用相同的代碼(否則,可以在2.6中使用repr ,在Python 3中使用ascii ,但這並不是真正的“相同” ;-)。

我無法重現您的問題,請查看此答案的先前版本,以獲取我的嘗試記錄(該注釋在評論中解釋了我的鏈接)。

然而:

看來您正在嘗試通過自己做所有的繁瑣工作來在寫入文件時強制編碼。 但是在Python 3中, open()接受一個encoding參數,該參數可以為您完成所有工作。

badp@delta:~$ python3
Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = open("look mah, utf-32", "w", encoding="utf-32")
>>> foo.write("bar")
3
>>> foo.close()
>>> foo = open("look mah, utf-32", "rb")
>>> foo.read()
b'\xff\xfe\x00\x00b\x00\x00\x00a\x00\x00\x00r\x00\x00\x00'

如果您正在尋找等效的Python 2,似乎您真的想使用io.open()

http://docs.python.org/py3k/library/functions.html#ascii

作為repr(),返回一個包含對象可打印表示形式的字符串,但是使用\\ x,\\ u或\\ U轉義符對repr()返回的字符串中的非ASCII字符進行轉義。 這將生成類似於Python 2中repr()返回的字符串。

結果字符串確實將是str類型而不是bytes類型。

例:

>>> a = '''Ⴊ ⇠ ਐ ῼ இ ╁ ଠ ୭ ⅙ ㈣'''
>>> ascii(a)
"'\\u10aa \\u21e0 \\u0a10 \\u1ffc \\u0b87 \\u2541 \\u0b20 \\u0b6d \\u2159 \\u3223'"
>>> print(ascii(a))
'\u10aa \u21e0 \u0a10 \u1ffc \u0b87 \u2541 \u0b20 \u0b6d \u2159 \u3223'

而且,如果您想減少多余的引號,則可以執行print(ascii(a)[1:-1])

編輯:正如Alex所述,您必須在Python 2.6中使用repr而不是ascii 他的解決方案確實適用於Python 2和3,但是如果您打算進行大量轉換(因此更喜歡多次鍵入內容),一種可能性是在程序的開始處添加條件,如下所示:

import sys
if sys.version_info[0] == 3:
    unic = ascii
else:
    unic = repr

然后,無論您在Python 2中使用repr還是在Python 3中使用ascii任何地方,都可以使用unic (或任何您想調用的名稱)。

...雖然我想您可以使用elif sys.version_info[0] == 2:而不是else:如果您想更加小心一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM