Python chr()函数返回错误的字符

问题描述 投票:1回答:1

我正在尝试编写一个简单的程序:在while循环中,它接受整数(保证在0,255范围内),将其转换为相应的字符并将此字符写入文件,直到输入整数为-1。我用C ++编写它并且效果很好。代码是:

#include <iostream>
#include <fstream>
using namespace std;

int main(){
    char c;
    int p;

    ofstream myfile;
    myfile.open ("a.txt");

    while(true){
        cin>>p;
        if(p == -1)
            break;
        c = p;

        myfile << c;
    }

    return 0;
}

我也尝试在python 3中编写相同的程序,代码是:

import sys

file = open("b.txt", "w")
while True:
    p = int(input())
    if p == -1:
        break
    c = chr(p)
    file.write(c)

问题是,在某些输入上,它们提供不同的输出,例如输入:

0
3
38
58
41
0
194
209
54
240
59
-1

C ++提供输出:

0003 263a 2900 c2d1 36f0 3b

和python给出输出:

0003 263a 2900 c382 c391 36c3 b03b 

我有测试用例,所以我知道C ++的输出是正确的。可能是什么问题?

python file char int
1个回答
2
投票

你的“角色”概念似乎是“字节”。 Python不是; Python 3的“字符”概念是“Unicode代码点”,它们如何转换为字节取决于编码。

如果你想写字节,你应该以二进制模式(在C ++和Python中)打开你的文件,你应该改变你的Python代码以将bytes对象传递给write

with open("b.txt", "wb") as file:
    while True:
        p = int(input())
        if p == -1:
            break
        # file.write(bytearray([p])) for Python 2 compatibility
        file.write(bytes([p]))
© www.soinside.com 2019 - 2024. All rights reserved.