标签: gbk

在Python中打印包含中文字符的列表

我的代码看起来像:

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

print ["asdf", "??"]
print ["??"]
print "??"
Run Code Online (Sandbox Code Playgroud)

Eclipse控制台中的输出非常奇怪:

['asdf', '\xe4\xb8\xad\xe6\x96\x87']
['\xe4\xb8\xad\xe6\x96\x87']
??
Run Code Online (Sandbox Code Playgroud)

我的第一个问题是:为什么最后一行得到正确的输出,而其他的没有?

我的第二个问题是:如何纠正错误的(使它们输出真实的字符而不是以"x"开头的代码)

感谢你们!!

python utf-8 character-encoding codepages gbk

5
推荐指数
1
解决办法
6056
查看次数

为什么 file.tell() 会影响编码?

调用tell()在阅读我的GBK编码的文件会导致下一次调用readline()来养UnicodeDecodeError。但是,如果我不调用tell(),则不会引发此错误。

C:\tmp>hexdump badtell.txt

000000: 61 20 6B 0D 0A D2 BB B0-E3                       a k......
Run Code Online (Sandbox Code Playgroud)

C:\tmp> 输入 test.py

with open(r'c:\tmp\badtell.txt', "r", encoding='gbk') as f:
    while True:
        pos = f.tell()
        line = f.readline();
        if not line: break
        print(line)
Run Code Online (Sandbox Code Playgroud)

C:\tmp>python test.py

a k

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    line = f.readline();
UnicodeDecodeError: 'gbk' codec can't decode byte 0xd2 in position 0:  incomplete multibyte sequence
Run Code Online (Sandbox Code Playgroud)

当我删除该f.tell()语句时,它成功解码。为什么?我在Win7/Win10上试过Python3.4/3.5 x64,都是一样的。

任何人,任何想法?我应该报告错误吗? …

file-io character-encoding python-3.x gbk

5
推荐指数
1
解决办法
106
查看次数

在python中将GBK转换为utf8字符串

我有一个字符串.

s = u"<script language=javascript>alert('\xc7\xeb\xca\xe4\xc8\xeb\xd5\xfd\xc8\xb7\xd1\xe9\xd6\xa4\xc2\xeb,\xd0\xbb\xd0\xbb!');location='index.asp';</script></script>"
Run Code Online (Sandbox Code Playgroud)

我怎样才能翻译s成utf-8字符串?我试过s.decode('gbk').encode('utf-8')但是python报告错误:UnicodeEncodeError: 'ascii' codec can't encode characters in position 35-50: ordinal not in range(128)

python utf-8 gbk

2
推荐指数
1
解决办法
9351
查看次数