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

Categories

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

python - I want to decode to "UTF-8"

The restoration and rejuvenation of the Willamette Army Basexe2x80x94now the Willamette Reservist Training Centerxe2x80x94is complete.  
 

I need to decode all these to "UTF-8" except " ". So i want this output

Original :The restoration and rejuvenation of the Willamette Army Basexe2x80x94now the Willamette Reservist Training Centerxe2x80x94is complete.  
 

Decoded : The restoration and rejuvenation of the Willamette Army Base—now the Willamette Reservist Training Center—is complete.  
 

question from:https://stackoverflow.com/questions/65858888/i-want-to-decode-to-utf-8

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

1 Reply

0 votes
by (71.8m points)

Your input string must be a byte string for decoding to make sense. Assuming that use bytes.decode():

>>> s = b'The restoration and rejuvenation of the Willamette Army Basexe2x80x94now the Willamette Reservist Training Centerxe2x80x94is complete.  
 
'
>>> type(s)
<class 'bytes'>
>>> s2 = s.decode('utf8')
>>> type(s2)
<class 'str'>
>>> s2
'The restoration and rejuvenation of the Willamette Army Base—now the Willamette Reservist Training Center—is complete.  
 
'

The above shows decoding of a byte string (class bytes) to a unicode string (class str).

Strip off the trailing new lines with rstrip():

>>> s2.rstrip()
'The restoration and rejuvenation of the Willamette Army Base—now the Willamette Reservist Training Center—is complete.'

If your data is coming from a file or other stream you can decode as you read it by specifying an encoding when you open the file/stream:

with open('file.txt', encoding='utf8') as f:
    for line in f:
        print(line)

This will decode the incoming data from UTF8 and your code only deals with strings. not byte strings. See open() for details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...