为什么Python String连接与俄语文本一起使用但string.format()不能

Jas*_*ske 2 python csv character-encoding windows-1251

我正在尝试解析(并转义)存储在Windows-1251字符编码中的CSV文件的行.使用这个优秀的答案来处理这种编码我最终得到了这一行来测试输出,由于某种原因,这是有效的:

print(row[0]+','+row[1])
Run Code Online (Sandbox Code Playgroud)

输出:

??????? ??????? ???????????,1 ????
Run Code Online (Sandbox Code Playgroud)

虽然这条线不起作用:

print("{0},{1}".format(*row))
Run Code Online (Sandbox Code Playgroud)

输出此错误:

Name,Variant

Traceback (most recent call last):
  File "Russian.py", line 26, in <module>
    print("{0},{1}".format(*row))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2-3: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

以下是CSV的前两行:

Name,Variant
??????? ??????? ???????????,1 ????
Run Code Online (Sandbox Code Playgroud)

如果它有帮助,这里是Russian.py的完整来源:

import csv
import cgi
from chardet.universaldetector import UniversalDetector
chardet_detector = UniversalDetector()

def charset_detect(f, chunk_size=4096):
    global chardet_detector
    chardet_detector.reset()
    while 1:
        chunk = f.read(chunk_size)
        if not chunk: break
        chardet_detector.feed(chunk)
        if chardet_detector.done: break
    chardet_detector.close()
    return chardet_detector.result

with open('Russian.csv') as csv_file:
    cd_result = charset_detect(csv_file)
    encoding = cd_result['encoding']
    csv_file.seek(0)
    csv_reader = csv.reader(csv_file)
    for bytes_row in csv_reader:
        row = [x.decode(encoding) for x in bytes_row]
        if len(row) >= 6:
            #print(row[0]+','+row[1])
            print("{0},{1}".format(*row))
Run Code Online (Sandbox Code Playgroud)

Ziz*_*212 6

列表中的字符串可能已经是unicode,因此您没有遇到问题.

print(row[0]+','+row[1])
??????? ??????? ???????????,1 ????
Run Code Online (Sandbox Code Playgroud)

但是在这里我们尝试将unicode添加到普通字符串中!这就是你得到的原因UnicodeEncodeError.

print("{0},{1}".format(*row))
Run Code Online (Sandbox Code Playgroud)

所以只需将其更改为:

print(u"{0}, {1}".format(*row))
Run Code Online (Sandbox Code Playgroud)