python 编码总结

本文介绍了Python中处理字符编码的方法,包括设置默认编码为UTF-8,将字符串转换为Unicode,以及使用自定义JSON编码器来处理特殊类型如Decimal和datetime。这些技巧对于解决常见的编码问题和提高数据处理效率非常实用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、#coding:utf-8

2、import sys

       import sys

       reload(sys)
       sys.setdefaultencoding('utf-8')


3、解码为unicode

 60 def strdecode(sentence):
 61     if not isinstance(sentence, unicode):
 62         try:
 63             sentence = sentence.decode('utf-8')
 64         except UnicodeDecodeError:
 65             sentence = sentence.decode('gbk', 'ignore')
 66     return sentenc

4、汉字字符串按下标操作时,需decode为unicode


5、json 处理Decima datetime.datetime

 20 class DecimalJSONEncoder(json.JSONEncoder):
 21     def default(self, o):
 22         if isinstance(o, decimal.Decimal):
 23             return str(o)
 24         return super(DecimalJSONEncoder, self).default(o)
  json.dumps(result,cls=DecimalJSONEncoder)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值