Skip to the workspace
Pebellslearn by building
Strings  ›  Lesson

APPEND and STRLEN

APPEND 12 minAPPEND adds text to the end of a string and replies with the new length, and STRLEN replies with a string's length in bytes, or 0 for a missing key.

redis / APPEND and STRLEN

Explore each scene at your own pace.

01 · The rule

The rule

APPEND and STRLEN

Wordcraft keeps a tiny text log of each player's recent results: won,won,lost,. Rewriting the whole log after every game means reading it, changing it in the app and sending it all back. Redis can simply add to the end of the string, and measure it, without the value ever leaving the server.

The rule

APPEND grows the string and replies with its length; STRLEN only measures.

APPEND key text adds text to the end of the string at key and replies with the new length in bytes, not with the text. If the key does not exist, APPEND creates it, exactly like SET.

STRLEN key replies with the length of the string in bytes. A missing key has length 0, not (nil).

127.0.0.1:6379> APPEND log:asha "won,"
(integer) 4
127.0.0.1:6379> APPEND log:asha "won,"
(integer) 8
127.0.0.1:6379> APPEND log:asha "lost,"
(integer) 13
127.0.0.1:6379> STRLEN log:asha
(integer) 13
127.0.0.1:6379> GET log:asha
"won,won,lost,"
127.0.0.1:6379> STRLEN log:nobody
(integer) 0

Bytes, not letters. Redis strings are byte sequences, so lengths are counted in bytes. Plain English letters are one byte each, but many characters take more in UTF-8: STRLEN of "café" is 5, because é takes two bytes.

Numbers count as text. After SET coins:asha 120, STRLEN coins:asha replies 3, the number of digits, and APPEND coins:asha 0 turns it into "1200". Handy to know, dangerous to do by accident.

Like GET, both commands only work on strings; on a hash or list they reply with a WRONGTYPE error.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.