Python-redis keys() returns list of bytes objects instead of strings

Solution 1:

You can configure the Redis client to automatically convert responses from bytes to strings using the decode_responses argument to the StrictRedis constructor:

r = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True)

Make sure you are consistent with the charset option between clients.

Note

You would be better off using the EXISTS command and restructuring your code like:

string = 'abcde'
if redis.exists(string):
    do something..

The KEYS operation returns every key in your Redis database and will cause serious performance degradation in production. As a side effect you avoid having to deal with the binary to string conversion.

Solution 2:

If you do not wish to iterate the list for decoding, set your redis connection to automagically perform the decode and you'll receive your required result. As follows in your connection string, please notice the decode_responses argument:

rdb = redis.StrictRedis(host="localhost", port=6379, db=0, decode_responses=True)

Happy Coding! :-) (revised 13 Nov 2019)