我有一個Python 3程序,讀取從Windows 1252編碼文件某些字符串:打印與編碼到標準輸出,在Python 3
with open(file, 'r', encoding="cp1252") as file_with_strings:
# save some strings
這是我後來想寫入標準輸出。我試過這樣做:
print(some_string)
# => UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 180: ordinal not in range(128)
print(some_string.decode("utf-8"))
# => AttributeError: 'str' object has no attribute 'decode'
sys.stdout.buffer.write(some_str)
# => TypeError: 'str' does not support the buffer interface
print(some_string.encode("cp1252").decode("utf-8"))
# => UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 180: invalid continuation byte
print(some_string.encode("cp1252"))
# => has the unfortunate result of printing b'<my string>' instead of just the string
我在這裏撓我的腦袋。我想在cp1252中打印出我從文件中得到的字符串。 (在我的終端中,當我做more $file
時,這些字符顯示爲問號,所以我的終端可能是ascii。)
想了解一下!謝謝!
什麼'string_to_print = some_string.decode( 'UTF-8'); print(string_to_print)'do? – hd1
這只是一個str,所以我得到'AttributeError:'str'對象沒有屬性'decode'' –
「(在我的終端中,當我多做$文件時,這些字符顯示爲問號,所以我的終端可能是ascii 。)「< - 不,看起來好像在你的答案中寫着cp1252,那麼你的終端編碼可能與你的語言環境不匹配。 –