Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串从utf8编码转换为850_Python_R_Encoding - Fatal编程技术网

Python 将字符串从utf8编码转换为850

Python 将字符串从utf8编码转换为850,python,r,encoding,Python,R,Encoding,我有一个utf8编码的字符串,我想把它转换成850(编码)。我已经用像这样的R完成了,但我不知道如何用Python实现:iconv(曲线1,“UTF-8”,“850”,toRaw=TRUE) 谢谢 试试这个 string_utf = "your utf-8 encoded string" string_cp850 = string_utf.encode(encoding='cp850') 对于python 3.9 #-*- coding:utf-8 -*- import s

我有一个utf8编码的字符串,我想把它转换成850(编码)。我已经用像这样的R完成了,但我不知道如何用Python实现:iconv(曲线1,“UTF-8”,“850”,toRaw=TRUE)

谢谢

试试这个

string_utf = "your utf-8 encoded string"
string_cp850 = string_utf.encode(encoding='cp850')
对于python 3.9

#-*- coding:utf-8 -*-
import sys
a = 'This is a bit русские буквы.'
print ("sys.stdout.encoding",sys.stdout.encoding)
print('Original string:', a)
# Encoding in utf-8
encoded_bytes = a.encode('utf-8', 'replace')
print('Encoded string:', encoded_bytes)


decoded_cp1251 = encoded_bytes.decode('cp1251', 'replace')
decoded_cp866 = encoded_bytes.decode('cp866', 'replace')
decoded_utf8 = encoded_bytes.decode('utf-8', 'replace')

sys.stdout.reconfigure(encoding='cp1251')
print ("sys.stdout.encoding",sys.stdout.encoding)
print('Decoded string: 1251', decoded_cp1251)
sys.stdout.reconfigure(encoding='cp866')
print ("sys.stdout.encoding",sys.stdout.encoding)
print('Decoded string: 866', decoded_cp866)
sys.stdout.reconfigure(encoding='utf-8')
print ("sys.stdout.encoding",sys.stdout.encoding)
print('Decoded string: utf-8', decoded_utf8)
例如,输出

PS C:\Users\Dmitry\PycharmProjects\python_sqlplus> python .\test_decode2.py
sys.stdout.encoding utf-8
Original string: This is a bit русские буквы.
Encoded string: b'This is a bit \xd1\x80\xd1\x83\xd1\x81\xd1\x81\xd0\xba\xd0\xb8\xd0\xb5 \xd0\xb1\xd1\x83\xd0\xba\xd0\xb2\xd1\x8b.'
sys.stdout.encoding cp1251
Decoded string: 1251 This is a bit русские буквы.
sys.stdout.encoding cp866
Decoded string: 866 This is a bit русские буквы.
sys.stdout.encoding utf-8
Decoded string: utf-8 This is a bit русские буквы.
PS C:\Users\Dmitry\PycharmProjects\python_sqlplus>

欢迎来到堆栈溢出。请用两分钟的时间。然后,您要提供的问题。您提供的代码会引发以下错误:“扩展”对象没有“重新配置”属性。我不知道这是否是我的错,但我复制了它。该代码适用于Python3.9,因为Python3.7您可以使用reconfigure()更改标准流的编码:我已经尝试过该函数,但它不会给出与R代码相同的结果,这就是为什么我要努力完成此任务的原因。你知道为什么不一样吗?