One place for hosting & domains


      How To Manage Strings in Redis


      Redis is an open-source, in-memory key-value data store. In Redis, strings are the most basic type of value you can create and manage. This tutorial provides an overview of how to create and retrieve strings, as well as how to manipulate the values held by string keys.

      How To Use This Guide
      This guide is written as a cheat sheet with self-contained examples. We encourage you to jump to any section that is relevant to the task you’re trying to complete.

      The commands and outputs shown in this guide were tested on an Ubuntu 18.04 server running Redis version 4.0.9. To obtain a similar setup, you can follow Step 1 of our guide on How To Install and Secure Redis on Ubuntu 18.04. We will demonstrate how these commands behave by running them with redis-cli, the Redis command line interface. Note that if you’re using a different Redis interface — Redli, for example — the exact outputs of certain commands may differ.

      Alternatively, you could provision a managed Redis database instance to test these commands, but note that depending on the level of control allowed by your database provider, some commands in this guide may not work as described. To provision a DigitalOcean Managed Database, follow our Managed Databases product documentation. Then, you must either install Redli or set up a TLS tunnel in order to connect to the Managed Database over TLS.

      Creating and Managing Strings

      Keys that hold strings can only hold one value; you cannot store more than one string in a single key. However, strings in Redis are binary-safe, meaning a Redis string can hold any kind of data, from alphanumeric characters to JPEG images. The only limit is that strings must be 512 MB long or less.

      To create a string, use the set command. For example, the following set command creates a key named key_Welcome1 that holds the string "Howdy":



      To set multiple strings in one command, use mset:

      • mset key_Welcome2 "there" key_Welcome3 "partners,"

      You can also use the append command to create strings:

      • append key_Welcome4 "welcome to Texas"

      If the string was created successfully, append will output an integer equal to how many characters the string includes:


      (integer) 16

      Note that append can also be used to change the contents of strings. See the section on manipulating strings for details on this.

      Retrieving Strings

      To retrieve a string, use the get command:



      To retrieve multiple strings with one command, use mget:

      • mget key_Welcome1 key_Welcome2 key_Welcome3 key_Welcome4


      1) "Howdy" 2) "there" 3) "partners," 4) "welcome to Texas"

      For every key passed to mget that doesn’t hold a string value or doesn’t exist at all, the command will return nil.

      Manipulating Strings

      If a string is made up of an integer, you can run the incr command to increase it by one:


      (integer) 4

      Similarly, you can use the incrby command to increase a numeric string’s value by a specific increment:


      (integer) 20

      The decr and decrby commands work the same way, but they decrease the integer stored in a numeric string:


      (integer) 19


      (integer) 3

      If an alphabetic string already exists, append will append the value onto the end of the existing value and return the new length of the string. To illustrate, the following command appends ", y'all" to the string held by the key key_Welcome4, so now the string will read "welcome to Texas, y'all":

      • append key_Welcome4 ", y'all"


      (integer) 15

      You can also append integers to a string holding a numeric value. The following example appends 45 to 3, the integer held in key_1, so it will then hold 345. In this case, append will also return the new length of the string, rather than its new value:


      (integer) 3

      Because this key still only holds a numeric value, you can perform the incr and decr operations on it. You can also append alphabetic characters to an integer string, but if you do this then running incr and decr on the string will produce an error as the string value is no longer an integer.


      This guide details a number of commands used to create and manage strings in Redis. If there are other related commands, arguments, or procedures you’d like to see outlined in this guide, please ask or make suggestions in the comments below.

      For more information on Redis commands, see our tutorial series on How to Manage a Redis Database.

      Source link

      An Introduction to the Strings Package in Go


      Go’s string package has several functions available to work with the string data type. These functions let us easily modify and manipulate strings. We can think of functions as being actions that we perform on elements of our code. Built-in functions are those that are defined in the Go programming language and are readily available for us to use.

      In this tutorial, we’ll review several different functions that we can use to work with strings in Go.

      Making Strings Uppercase and Lowercase

      The functions strings.ToUpper and strings.ToLower will return a string with all the letters of an original string converted to uppercase or lowercase letters. Because strings are immutable data types, the returned string will be a new string. Any characters in the string that are not letters will not be changed.

      Let’s convert the string "Sammy Shark" to be all uppercase:

      ss := "Sammy Shark"



      Now, let’s convert the string to be all lowercase:



      sammy shark

      Since you are using the strings package, you first need to import it into your program. To convert the string to uppercase and lowercase the entire program would be as follows:

      package main
      import (
      func main() {
          ss := "Sammy Shark"

      The strings.ToUpper and strings.ToLower functions make it easier to evaluate and compare strings by making case consistent throughout. For example, if a user writes their name all lowercase, we can still determine whether their name is in our database by checking it against an all uppercase version.

      String Search Functions

      The strings package has a number of functions that help determine if a string contains a specific sequence of characters.

      Function Use
      strings.HasPrefix Searches the string from the beginning
      strings.HasSuffix Searches the string from the end
      strings.Contains Searches anywhere in the string
      strings.Count Counts how many times the string appears

      The strings.HasPrefix and strings.HasSuffix allow you to check to see if a string starts or ends with a specific set of characters.

      Let’s check to see if the string Sammy Shark starts with Sammy and ends with Shark.

      ss := "Sammy Shark"
      fmt.Println(strings.HasPrefix(ss, "Sammy"))
      fmt.Println(strings.HasSuffix(ss, "Shark"))


      true true

      Let’s check to see if the string Sammy Shark contains the sequence Sh:

      fmt.Println(strings.Contains(ss, "Sh"))



      Finally, let’s see how many times the letter S appears in the phrase Sammy Shark:

      fmt.Println(strings.Count(ss, "S"))



      Note: All strings in Go are case sensitive. This means that Sammy is not the same as sammy.

      Using a lowercase s to get a count from Sammy Shark is not the same as using uppercase S:

      fmt.Println(strings.Count(ss, "s"))



      Because S is different than s, the count returned will be 0.

      String functions are useful when you want to compare or search strings in your program.

      Determining String Length

      The built-in function len() returns the number of characters in a string. This function is useful for when you need to enforce minimum or maximum password lengths, or to truncate larger strings to be within certain limits for use as abbreviations.

      To demonstrate this function, we’ll find the length of a sentence-long string:

      openSource := "Sammy contributes to open source."



      We set the variable openSource equal to the string "Sammy contributes to open source." and then passed that variable to the len() function with len(openSource). Finally we passed the function into the fmt.Println() function so that we could see the program’s output on the screen..

      Keep in mind that the len() function will count any character bound by double quotation marks—including letters, numbers, whitespace characters, and symbols.

      Functions for String Manipulation

      The strings.Join, strings.Split, and strings.ReplaceAll functions are a few additional ways to manipulate strings in Go.

      The strings.Join function is useful for combining a slice of strings into a new single string.

      Let’s create a comma-separated string from a slice of strings:

      fmt.Println(strings.Join([]string{"sharks", "crustaceans", "plankton"}, ","))



      If we want to add a comma and a space between string values in our new string, we can simply rewrite our expression with a whitespace after the comma: strings.Join([]string{"sharks", "crustaceans", "plankton"}, ", ").

      Just as we can join strings together, we can also split strings up. To do this, we use the strings.Split function and split on the spaces:

      balloon := "Sammy has a balloon."
      s := strings.Split(balloon, " ")


      [Sammy has a balloon]

      The output is a slice of strings. Since strings.Println was used, it is hard to tell what the output is by looking at it. To see that it is indeed a slice of strings, use the fmt.Printf function with the %q verb to quote the strings:

      fmt.Printf("%q", s)


      ["Sammy" "has" "a" "balloon."]

      Another useful function in addition to strings.Split is strings.Fields. The difference is that strings.Fields will ignore all whitespace, and will only split out the actual fields in a string:

      data := "  username password     email  date"
      fields := strings.Fields(data)
      fmt.Printf("%q", fields)


      ["username" "password" "email" "date"]

      The strings.ReplaceAll function can take an original string and return an updated string with some replacement.

      Let’s say that the balloon that Sammy had is lost. Since Sammy no longer has this balloon, we will change the substring "has" from the original string balloon to "had" in a new string:

      fmt.Println(strings.ReplaceAll(balloon, "has", "had"))

      Within the parentheses, first is balloon the variable that stores the original string; the second substring "has" is what we want to be replaced, and the third substring "had" is what we are replacing that second substring with. Our output will look like this:


      Sammy had a balloon.

      Using the string function strings.Join, strings.Split, and strings.ReplaceAll will provide you with greater control to manipulate strings in Go.


      This tutorial went through some of the common string package functions for the string data type that you can use to work with and manipulate strings in your Go programs.

      You can learn more about other data types in Understanding Data Types and read more about strings in An Introduction to Working with Strings.

      Source link

      How To Format Strings in Go

      As strings are often made up of written text, there are many instances when we may want to have greater control over how strings look to make them more readable for humans through punctuation, line breaks, and indentation.

      In this tutorial, we’ll go over some of the ways we can work with Go strings to make sure that all output text is formatted correctly.

      String Literals

      Let’s first differentiate between a string literal and a string value. A string literal is what we see in the source code of a computer program, including the quotation marks. A string value is what we see when we call the fmt.Println function and run the program.

      In the “Hello, World!” program, the string literal is "Hello, World!" while the string value is Hello, World! without the quotation marks. The string value is what we see as the output in a terminal window when we run a Go program.

      But some string values may need to include quotation marks, like when we are quoting a source. Because string literals and string values are not equivalent, it is often necessary to add additional formatting to string literals to ensure that string values are displayed the way in which we intend.


      Because we can use back quotes (`) or double quotes (") within Go, it is simple to embed quotes within a string by using double quotes within a string enclosed by back quotes:

      `Sammy says, "Hello!"`

      Or, to use a back quote, you can enclose the string in double quotes:

      "Sammy likes the `fmt` package for formatting strings.."

      In the way we combine back quotes and double quotes, we can control the display of quotation marks and back quotes within our strings.

      It’s important to remember that using back quotes in Go creates a raw string literal, and using double quotes creates an interpreted string literal. To learn more about the difference, read the An Introduction to Working with Strings in Go tutorial.

      Escape Characters

      Another way to format strings is to use an escape character. Escape characters are used to tell the code that the following character has a special meaning. Escape characters all start with the backslash key () combined with another character within a string to format the given string a certain way.

      Here is a list of several of the common escape characters:

      Escape Character How it formats
      \ Backslash
      Double Quote
      n Line Break
      t Tab (horizontal indentation)

      Let’s use an escape character to add the quotation marks to the example on quotation marks above, but this time we’ll use double quotes to denote the string:

      fmt.Println("Sammy says, "Hello!"")


      Sammy says, "Hello!"

      By using the escape character " we are able to use double quotes to enclose a string that includes text quoted between double quotes.

      We can use the n escape character to break lines without hitting the enter or return key:

      fmt.Println("This stringnspans multiplenlines.")


      This string spans multiple lines.

      We can combine escape characters, too. Let’s print a multi-line string and include tab spacing for an itemized list, for example:



      1. Shark 2. Shrimp 10. Squid

      The horizontal indentation provided with the t escape character ensures alignment within the second column in the preceding example, making the output extremely readable for humans.

      Escape characters are used to add additional formatting to strings that may be difficult or impossible to achieve. Without escape characters, you would not be able to construct the string Sammy says, "I like to use the `fmt` package".

      Multiple Lines

      Printing strings on multiple lines can make text more readable to humans. With multiple lines, strings can be grouped into clean and orderly text, formatted as a letter, or used to maintain the linebreaks of a poem or song lyrics.

      To create strings that span multiple lines, back quotes are used to enclose the string. Keep in mind that while this will preserve the line returns, it is also creating a raw string literal.

      This string is on 
      multiple lines
      within three single 
      quotes on either side.

      You will notice if you print this that there is a leading and trailing return:


      This string is on multiple lines within three single quotes on either side.

      To avoid this, you need to put the first line immediately following the back quote and end the last with the back quote.

      `This string is on 
      multiple lines
      within three single 
      quotes on either side.`

      If you need to create an interpreted string literal, this can be done with double quotes and the + operator, but you will need to insert your own line breaks.

      "This string is onn" +
      "multiple linesn" +
      "within three singlen" +
      "quotes on either side."

      While back quotes can make it easier to print and read lengthy text, if you need an interpreted string literal, you will need to use double quotes.

      Raw String Literals

      What if we don’t want special formatting within our strings? For example, we may need to compare or evaluate strings of computer code that use the backslash on purpose, so we won’t want Go to use it as an escape character.

      A raw string literal tells Go to ignore all formatting within a string, including escape characters.

      We create a raw string by using back quotes around the string:

      fmt.Println(`Sammy says,"The balloon's color is red."`)


      Sammy says,"The balloon's color is red."

      By constructing a raw string by using back quotes around a given string, we can retain backslashes and other characters that are used as escape characters.


      This tutorial went over several ways to format text in Go through working with strings. By using techniques such as escape characters or raw strings, we are able to ensure that the strings of our program are rendered correctly on-screen so that the end user is able to easily read all of the output text.

      Source link