Python字符串問題
python3版本
# 將str或字節并始終返回strdef to_str(bytes_or_str): if isinstance(bytes_or_str, bytes): value = bytes_or_str.decode(‘utf-8') else: value = bytes_or_str return value# 將str或字節并始終返回bytesdef to_bytes(bytes_or_str): if isinstance(bytes_or_str, str): value = bytes_or_str.encode(‘utf-8') else: value = bytes_or_str return value
python2版本
- 在python2版本中使用unicode方式
# 接受str或unicode,并總是返回unicodedef to_unicode(unicode_or_str): if isinstance(unicode_or_str, str): value = unicode_or_str.decode(‘utf-8') else: value = unicode_or_str return value # 接受str或unicode,并總是返回strdef to_str(unicode_or_str): if isinstance(unicode_or_str, unicode): value = unicode_or_str.encode(‘utf-8') else: value = unicode_or_str return value
備注
在python中不管任何版本,都是用 bytes的方式進行讀取 寫入會極大程度降低出現文本問題
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接
新聞熱點
疑難解答