当前位置:   article > 正文

python2.7运行报警告:UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode

unicodewarning: unicode equal comparison failed to convert both arguments to

一、报错信息

python代码

#coding=utf-8

from flask import Flask, request
import json

app = Flask(__name__)

@app.route('/api/user1', methods=['POST'])
def get_user1():
    user = data['data'][0] == '张三'
    print("用户:",user)	
    return data
	
if __name__ == '__main__':
    app.run(debug=True,port=8999)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

请求示例:
在这里插入图片描述

报错信息

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
  user = data['data'][0] == '寮犱笁'
('\xe7\x94\xa8\xe6\x88\xb7\xef\xbc\x9a', False)
  • 1
  • 2
  • 3

二、原因及解决方法

uncode编码警告:在unicode等价比较中,把两个参数同时转换为unicode编码失败。中断并认为他们不相等。

windows下的字符串str默认编码是ascii,而python编码是utf8

解决办法:
在代码中加入如下:
import sys
reload(sys)
sys.setdefaultencoding(‘utf8’)

修改后代码:

#coding=utf-8

from flask import Flask, request
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')

app = Flask(__name__)

@app.route('/api/user1', methods=['POST'])
def get_user1():
    user = data['data'][0] == '张三'
    print("用户:",user)	
    return data
	
if __name__ == '__main__':
    app.run(debug=True,port=8999)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/882522
推荐阅读
相关标签
  

闽ICP备14008679号