python3读取redis数据带有‘b’的问题
#encoding=utf-8
from redis import *
#读取数据
d1=input("您输入的数据是:")
#连接
r=StrictRedis(host='localhost',port=6379)
#写
# pipe=r.pipeline()
# pipe.set('r1','hello')
# pipe.set('r2','world')
# pipe.execute()
#读
#在python3的前面,有一个'b'代表的是bytes
#用以下方式解决
#注意,有值则进行编码
#法1:
# temp=r.get('r1').decode()
# print(temp)
#法2:
# temp=r.get('r2')
# h1=str(temp,encoding='utf-8')
# print(h1)
#如果没有值,则为None
s=r.get(d1)
print(s)
if s==None:
print('yes')
else:
print('no')
temp=s.decode()
print(temp)基本代码
from redis import *
if __name__ == '__main__':
sr = StrictRedis(host='localhost', port=6379, db=0)
result=sr.set('name','python')
print(result)
result1 = sr.get('name')
print(result1)运行结果:
True
b'python'
这里我们存进去的是字符串类型的数据,取出来却是字节类型的,这是由于python3的与redis交互的驱动的问题,Python2取出来的就是字符串类型的。
为了得到字符串类型的数据,你可以每次取出来decode一下,但是太繁琐了,可以这样设置:
sr = StrictRedis(host='localhost', port=6379, db=0,decode_responses=True)
即在连接数据库的时候加上decode_responses=True即可
Python如何把redis取出的数据去掉b
解决办法一
将链接转换为字符串类型,使用如下命令
temp.decode()
解决办法二
str(temp,encoding='utf-8')
解决办法三
在连接redis时进行设置,避免频繁地进行转换操作
StrictRedis(host='localhost', port=6379, db=0,decode_responses=True)
原因
Python3与redis交互驱动上存在问题,如果使用python2则不会出现这样的问题。
同样在python3打印数据中b'开头的代表的是bytes类型数据。
这个问题一定要牢记,避免在程序进行判断时出现问题而花费较多时间去排查。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好代码网。




