我有一个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,那么你的终端编码可能与你的语言环境不匹配。 –