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":

  • set key_Welcome1 "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:

  • get key_Welcome1

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:

  • set key_1 3
  • incr key_1
(integer) 4

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

  • incrby key_1 16
(integer) 20

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

  • decr key_1
(integer) 19
  • decrby key_1 16
(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:

  • append key_1 45
(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.

DigitalOcean Community Tutorials

Reuven Lerner: Playing with Python strings, lists, and variable names — or, a complex answer to a simple question

I recently received a question from a reader of my “Better developers” list. He asks:

Is there any way to turn a str type into a list type? For example, I have a list of elements, and want to turn that element into a separate list. For example, if I have

test = ['a', 'b', 'c']

I want the output to be

a=[], b=[], c=[]

One of the mantras of Python is that there should be one, and only one, way to do something. Reality has a way of being more complex than that, though, and in this particular case, the problem that my reader described in words and what he put in code weren’t exactly the same thing. (Which is a common problem in the professional software world — the specifications say one thing, but the client’s intentions say another.)

Let’s start with what my reader says he wants to do, and then get to what he actually seems to want:

He says that he wants to turn a string into a list. Well, there are a few ways to do that. The easiest is to use the “list” class, and apply it to a function:

He says that he wants to turn a string into a list. Well, there are a few ways to do that. The easiest is to use the “list” class, and apply it to a function:

>>> s = 'abc' >>> mylist = list(s) >>> mylist ['a', 'b', 'c']         

In such a case, the “list” class (which can be called, like a function, and is thus known as a “callable” in the Python world) iterates over the elements of our string. Each element is turned into a separate element in a new list that it returns.

This is fine if you want to create a new list with the same number of elements as there are characters in the string. After all, both strings and lists are Python sequences; when you create a list in this way, based on a string, you’ll find that the new list’s length and elements are identical. So s[0] and mylist[0] will return the same result, as will “len(s)” and “len(mylist)” even though “s” and “mylist” are different types.

Another way to create a list from a string is via the “str.split” method. I use this method all the time, especially when taking input from a user and iterating over the words, or fields, that the user provides. For example:

>>> words = 'here are some words' >>> words.split(' ') ['here', 'are', 'some', 'words']

The result of “str.split” is always a list of strings. And as you can see in the above example, we can tell “str.split” what string should be used as a field delimiter; “str.split” removes all occurrences of that string, returning a list of strings.

What happens if our string is a bit weird, though, such as:

>>> words = 'here    are some     words'

Now we’re going to get an equally weird result:

>>> words.split(' ') ['here', '', '', '', 'are', 'some', '', '', '', '', 'words']

This happens because “str.split” has taken our instructions very literally, as computers do: Whenever you encounter a space character, create a new element in the output list. However, this is rarely the solution that you want, and thus “str.split” has a great default: If you don’t pass anything (or pass “None” explicitly), then any length of whitespace characters will be treated as a single delimiter. Which means that we can say:

>>> words = 'here    are some     words' >>> words.split() ['here', 'are', 'some', 'words']

This is quite useful… and yet, while this is how I interpreted the question I got, it’s not what the user wants.

Rather, what he seems to want is to create new variables based on the elements of the string. So if the string is “abc”, then we want to create new variables “a”, “b”, and “c”, each of which references an empty list.

This is certainly possible, but I’ll admit it’s a bit odd. However, it gives us a chance to delve into some of Python’s more rarely used capabilities. (At least, I almost never use them — maybe other people are different!)

My first reaction to creating variables dynamically is to say, “No, you don’t really want to do that,” and to suggest that we create a dictionary, instead. You can think of a dict as your own private namespace, one which can’t and won’t interfere with the variables created elsewhere.

We could create an empty dictionary, and then iterate over the string, adding new key-value pairs to it, with each value being an empty list:

>>> for one_letter in 'abc':         d[one_letter] = []  >>> d {'a': [], 'b': [], 'c': []}

There is, however, a better way to do what we did here, and that is by using the “dict.fromkeys” class method. This is a great shortcut to creating a dictionary whose keys are known but whose values aren’t, at least not at the start. So we can say:

>>> dict.fromkeys('abc') {'a': None, 'b': None, 'c': None}

As you can see, the value associated with each key here is “None”. We don’t want that; instead, we want to have an empty list. So we can pass an empty list as a second, optional argument to “dict.fromkeys”:

>>> dict.fromkeys('abc', []) {'a': [], 'b': [], 'c': []} 

However, you should be a bit nervous before working with the dictionary I’ve created here, because every single one of the values now refers to the same list! For example:

>>> d = dict.fromkeys('abc', []) >>> d {'a': [], 'b': [], 'c': []} >>> d['a'].append(1) >>> d['b'].append(2) >>> d['c'].append(3) >>> d {'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}                

In many ways, this is similar to the problem of mutable defaults, in that we have a single value referenced in multiple places. It’s pretty obvious to experienced Python developers that this will happen, but it’s far from obvious to newcomers.

Another way to do this would be to use a dict comprehension:

>>> {one_letter : []      for one_letter in 'abc'} {'a': [], 'b': [], 'c': []}

“Wait,” you might be saying, “Maybe we have to worry about these lists also all referring to the same thing?”


>>> d = {one_letter : []          for one_letter in 'abc'} >>> d['a'].append(1) >>> d['b'].append(2) >>> d['c'].append(3) >>> d {'a': [1], 'b': [2], 'c': [3]}         

What’s the difference between this, and our previous use of “dict.fromkeys”? The difference is that here, the “[]” empty list is evaluated anew with each iteration over the string. Thus, we get a new empty list each time. By contrast, passing the same empty list as a second argument to “dict.fromkeys” gave us the same list each time.

So if you want to use a dict — and that’s my recommendation — then you are good to go! But if you really and truly want to create variables based on the values in the string, then we’ll have to use a few more tricks.

One is to take advantage of the fact that global variables are actually stored in a dictionary. Yes, that’s right — you might think that when you write “x=100” that you’re storing things in some magical location. But actually, Python turns your variable name into a string, and uses that string as a key into a dictionary.

We don’t have direct access to this dictionary, but we can retrieve it using the “globals” builtin function. Here’s what happens when I invoke “globals” in a brand-new Python 3 interactive shell:

>>> globals() {'__name__': 'main', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}         

See what happens now, after I assign some variables:

>>> x = 100 >>> y = [10, 20, 30] >>> z = {'a':1, 'b':2} >>> globals()          {'__name__': 'main', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 100, 'y': [10, 20, 30], 'z': {'a': 1, 'b': 2}}         

Take a look at the end, and you’ll see our three newly assigned variables.

It turns out that we can also define (or update the values of) global variables in this way, too:

>>> globals()['x'] = 234 >>> globals()['y'] = [9,8,7,6] >>> globals()['z'] = 'hello out there'          >>> globals() {'__name__': 'main', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'x': 234, 'y': [9, 8, 7, 6], 'z': 'hello out there'}

I don’t really recommend this in actual code, but if you’re absolutely, positively sure that you want to do this, then you can accomplish this task in the following way:

>>> for one_letter in 'abc':     globals()[one_letter] = []         

Sure enough:

>>> x [] >>> y [] >>> z []

Again, you almost certainly don’t want to have this sort of code in production. But it does work, as we see here.

Something else we could do is use the “exec” function, which lets us run any string as a tiny Python program. We could thus say:

>> for one_letter in 'abc':         exec(f'{one_letter} = []')  >>> a [] >>> b [] >>> c []         

As you can see, it worked: We used an f-string to create a tiny (one-statement) Python program, and then used “exec” to run it. Note that we wouldn’t be able to use the related “eval” function here, because “eval” expects to have an expression, and assignment in Python isn’t an expression.

Finally, I’d generally argue that it’s a good idea not to create or manipulate global variables whose names are created dynamically from the user’s input. It’s probably best (as I wrote above) to use a dictionary. However, if you really insist on doing this, then you should probably do it in a module.

But wait — aren’t modules normally defined in files? Yes, but you can create a module on the fly by running the “module” class, just as we did above with the “list” class. There’s just one hitch, namely that the “module” class isn’t available to us in any of the Python namespaces.

That’s OK: We can grab the class via another module (e.g., __builtins__), and then invoke it, passing it the name of the module we want to create. Then we can use the builtin “setattr” function to assign a new attribute to the module. Here’s how that would look:

>>> mymod = type(__builtins__)('mymod') >>> for one_letter in 'abc': setattr(mymod, one_letter, []) >>> vars(mymod) {'__name__': 'mymod', '__doc__': None, '__package__': None, '__loader__': None, '__spec__': None, 'a': [], 'b': [], 'c': []}         

Sure enough, we’ve managed to do it!

By the way, remember how I mentioned, all the way back, that it would probably be best to use a dictionary, rather than create actual variables? Well, as you can see here, a module is actually just a fancy wrapper around… a dictionary.

This seemingly simple question raised all sorts of interesting Python functionality, none of which (I’m guessing) was ever intended by the person who asked the question. But I hope that this has given you a glimpse into the ways in which Python has implemented, and how a dynamic language allows us to play with our environment in ways that not only stretch our minds, but sometimes even the boundaries of good taste.

The post Playing with Python strings, lists, and variable names — or, a complex answer to a simple question appeared first on Reuven Lerner.

Planet Python

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" fmt.Println(strings.ToUpper(ss)) 

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 (     "fmt"     "strings" )  func main() {     ss := "Sammy Shark"     fmt.Println(strings.ToUpper(ss))     fmt.Println(strings.ToLower(ss)) } 

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." fmt.Println(len(openSource)) 

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, " ") fmt.Println(s) 
[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.

DigitalOcean Community Tutorials

An Introduction to Working with Strings in Go

A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Made up of Unicode, strings are immutable sequences, meaning they are unchanging.

Because text is such a common form of data that we use in everyday life, the string data type is a very important building block of programming.

This Go tutorial will go over how to create and print strings, how to concatenate and replicate strings, and how to store strings in variables.

String Literals

In Go, strings exist within either back quotes ` (sometimes referred to as back ticks) or double quotes ". Depending on which quotes you use, the string will have different characteristics.

Using back quotes, as in `bar`, will create a raw string literal. In a raw string literal, any character may appear between quotes, with the exception of back quotes. Here’s an example of a raw string literal:

`Say "hello" to Go!` 

Backslashes have no special meaning inside of raw string literals. For instance, \n will appear as the actual characters, backslash \ and letter n. Unlike interpreted string literals, in which \n would insert an actual new line.

Raw string literals may also be used to create multi-line strings:

`Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multi-core and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.` 

Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear with the exception of newline and unescaped double quotes.

"Say \"hello\" to Go!" 

You will almost always use interpreted string literals because they allow for escape characters within them.

Now that you understand how strings are formatted in Go, let’s take a look at how you can print strings in programs.

Printing Strings

You can print out strings by using the fmt package from the system library and calling the Println() function:

fmt.Println("Let's print out this string.") 
Let's print out this string.

You have to import system packages when you use them, so a simple program to print out a string would look like this:

package main  import "fmt"  func main() {     fmt.Println("Let's print out this string.") } 

String Concatenation

Concatenation means joining strings together, end-to-end, to create a new string. You can concatenate strings with the + operator. Keep in mind that when you work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.

Let’s combine the string literals "Sammy" and "Shark" together with concatenation through a fmt.Println() statement:

fmt.Println("Sammy" + "Shark") 

If you would like a whitespace between the two strings, you can simply include the whitespace within a string. In this example, add the whitespace within the quotes after Sammy:

fmt.Println("Sammy " + "Shark") 
Sammy Shark

The + operator can not be used between two different data types. As an example, you can’t concatenate strings and integers together. If you were to try to write the following:

fmt.Println("Sammy" + 27) 

You will receive the following errors:

cannot convert "Sammy" (type untyped string) to type int invalid operation: "Sammy" + 27 (mismatched types string and int)

If you wanted to create the string "Sammy27", you could do so by putting the number 27 in quotes ("27") so that it is no longer an integer but is instead a string. Converting numbers to strings for concatenation can be useful when dealing with zip codes or phone numbers. For example, you wouldn’t want to perform addition between a country code and an area code, but you do want them to stay together.

When you combine two or more strings through concatenation, you are creating a new string that you can use throughout your program.

Storing Strings in Variables

Variables are symbols that you can use to store data in a program. You can think of them as an empty box that you fill with some data or value. Strings are data, so you can use them to fill up a variable. Declaring strings as variables can make it easier to work with strings throughout your Go programs.

To store a string inside a variable, simply assign a variable to a string. In this case, declare s as your variable:

s := "Sammy likes declaring strings." 

Note: If you’re familiar with other programming languages, you may have written the variable as sammy. Go, however, favors shorter variable names. Choosing s for the variable name in this case would be considered more appropriate for the style in which Go is written.

Now that you have the variable s set to that particular string, you can print the variable like so:


You will then receive the following output:

Sammy likes declaring strings.

By using variables to stand in for strings, you do not have to retype a string each time you want to use it, making it more simple for you to work with and manipulate strings within your programs.


This tutorial went over the basics of working with the string data type in the Go programming language. Creating and printing strings, concatenating and replicating strings, and storing strings in variables will provide you with the fundamentals to use strings in your Go programs.

DigitalOcean Community Tutorials

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 string\nspans multiple\nlines.") 
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 on\n" + "multiple lines\n" + "within three single\n" + "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.

DigitalOcean Community Tutorials