【问题标题】:Python redis returns results with appended text to result [duplicate]Python redis将带有附加文本的结果返回到结果[重复]
【发布时间】:2017-12-24 02:25:31
【问题描述】:

我刚开始在命令行和 jupyter 笔记本中使用 redis 和 python,我在这两个地方都得到了附加文本。代码如下:

import redis
r = redis.StrictRedis(host='123.456.789.123', port=6379, db=0, password='mypwd')

r.hmset('hmfoo', { 'name': 'myname', 'username': 'myusername'})
True

r.hget('hmfoo', 'name')
b'myname' <----- why is the 'b' appended here??

它可以像您期望的那样使用存储在 redis 和所有内容中的正确值,只是不确定为什么 b 显示在文本的开头

【问题讨论】:

标签: python redis


【解决方案1】:

原来它不是一个字符串,而是一个字节字符串结果,'b' 是为了表明这一点。您可以通过 armnotstrong What does the 'b' character do in front of a string literal? 提供的链接了解更多信息

但我在这篇 SO 帖子中找到了答案 About char b prefix in Python3.4.1 client connect to redis

要将结果作为字符串获取,您有 2 个选项:

1.在连接中设置编码(charset='utf-8', decode_responses=True)

2. 解码结果以转换为例如字符串 r.get('foo').decode('utf-8')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2015-06-26
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多