Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

python - convert a string from encoding utf8 to 850

I have a string encoded in utf8 and I want to convert it to 850 (encoding). I have done it with R like this but I don't know how to do it in Python: iconv(curve1,"UTF-8", "850", toRaw = TRUE)

Thank you!!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For 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)

Output for example

PS C:UsersDmitryPycharmProjectspython_sqlplus> python .est_decode2.py
sys.stdout.encoding utf-8
Original string: This is a bit русские буквы.
Encoded string: b'This is a bit xd1x80xd1x83xd1x81xd1x81xd0xbaxd0xb8xd0xb5 xd0xb1xd1x83xd0xbaxd0xb2xd1x8b.'
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:UsersDmitryPycharmProjectspython_sqlplus>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

33 comments

45.2k users

...