About char b prefix in Python3.4.1 client connect to redis
Question:
I am run into trouble .My code below.But I do not know why there is a char ‘b’ before output string “Hello Python”.
>>> import redis
>>> redisClient = redis.StrictRedis(host='192.168.3.88',port=6379)
>>> redisClient.set('test_redis', 'Hello Python')
True
>>> value = redisClient.get('test_redis')
>>> print(value)
b'Hello Python' //why char 'b' output?
Answers:
b'Hello Python'
is a byte string – redis will auto-encode a unicode string for you on the way in, but it’s your job to decode it on the way out.
Better to explicitly encode and decode:
>>> redisClient.set('test_redis', 'Hello Python'.encode('utf-8'))
>>> redisClient.get('test_redis').decode('utf-8')
'Hello Python'
It means it’s a byte string
You can use:
redis.StrictRedis(host="localhost", port=6379, charset="utf-8", decode_responses=True)
using decode_responses=True
to make a unicode string.
I am run into trouble .My code below.But I do not know why there is a char ‘b’ before output string “Hello Python”.
>>> import redis
>>> redisClient = redis.StrictRedis(host='192.168.3.88',port=6379)
>>> redisClient.set('test_redis', 'Hello Python')
True
>>> value = redisClient.get('test_redis')
>>> print(value)
b'Hello Python' //why char 'b' output?
b'Hello Python'
is a byte string – redis will auto-encode a unicode string for you on the way in, but it’s your job to decode it on the way out.
Better to explicitly encode and decode:
>>> redisClient.set('test_redis', 'Hello Python'.encode('utf-8'))
>>> redisClient.get('test_redis').decode('utf-8')
'Hello Python'
It means it’s a byte string
You can use:
redis.StrictRedis(host="localhost", port=6379, charset="utf-8", decode_responses=True)
using decode_responses=True
to make a unicode string.