Python中bytes與字符串的相互轉化


代碼:

復制代碼
# bytes轉字符串方式一
b=b'\xe9\x80\x86\xe7\x81\xab'
string=str(b,'utf-8')
print(string)

# bytes轉字符串方式二
b=b'\xe9\x80\x86\xe7\x81\xab'
string=b.decode() # 第一參數默認utf8,第二參數默認strict
print(string)

# bytes轉字符串方式三
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','ignore') # 忽略非法字符,用strict會拋出異常
print(string)

# bytes轉字符串方式四
b=b'\xe9\x80\x86\xe7\x81haha\xab'
string=b.decode('utf-8','replace') # 用?取代非法字符
print(string)

# 字符串轉bytes方式一
str1='逆火'
b=bytes(str1, encoding='utf-8')
print(b)

# 字符串轉bytes方式二
b=str1.encode('utf-8')
print(b)
復制代碼

輸出:

復制代碼
C:\Users\horn1\Desktop\python\42-torrentParser>python convert.py
逆火
逆火
逆haha
逆�haha�
b'\xe9\x80\x86\xe7\x81\xab'
b'\xe9\x80\x86\xe7\x81\xab'

C:\Users\horn1\Desktop\python\42-torrentParser>
復制代碼

 參考文章:https://www.cnblogs.com/chownjy/p/6625299.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM