Lesson 5 of 38 · Fundamentals
Go Strings and fmt.Sprintf Formatting
Text is everywhere: player names, shop menus, quest logs, error messages. Go strings are easy to use, but under the hood they work a little differently from many languages — knowing how saves you from some classic bugs.
You will also learn fmt.Sprintf, the tool Go programmers reach for whenever they need to build a piece of formatted text.
Strings are bytes
A Go string is an immutable sequence of bytes, normally holding UTF-8 encoded text. Plain ASCII characters such as G take one byte, letters like é take two, and most emoji take four. The built-in len counts bytes, not characters:
fmt.Println(len("Gopher")) // 6
fmt.Println(len("olé")) // 4: é takes two bytes
Indexing a string with s[i] gives you a single byte — a number, not a one-letter string. Slicing with s[start:end] returns the substring from byte start up to, but not including, byte end. Leave out start or end to slice from the beginning or to the end:
package main
import "fmt"
func main() {
s := "Gopher"
fmt.Println(s[0], s[1])
fmt.Println(s[0:2], s[2:])
fmt.Println(s[:1] + "!")
}
71 111
Go pher
G!
71 is the byte value of G. Strings are immutable: s[0] = 'g' does not compile. To "change" a string you build a new one, for example by concatenating strings with +. The lesson on loops shows how to walk through the characters of a string.
Escapes and raw strings
Double-quoted strings understand escape sequences such as \n (newline), \t (tab), \" and \\. Strings in backticks are raw: backslashes are ordinary characters and the string may span several lines:
path := `C:\games\gopher`
banner := `Welcome to
the Gopher Isles`
The strings package
The standard strings package covers everyday text work. Its functions never modify a string; they return a new one:
strings.ToUpper("go") // "GO"
strings.ToLower("GoPher") // "gopher"
strings.TrimSpace(" hi \n") // "hi"
strings.Contains("gopher", "ph") // true
strings.HasPrefix("gopher", "go") // true
strings.Repeat("ab", 3) // "ababab"
strings.Replace("a-b-c", "-", "+", -1) // "a+b+c" (-1 means all)
strings.Fields(" a b c ") // ["a" "b" "c"]
strings.Split("x,y,z", ",") // ["x" "y" "z"]
Fields splits on whitespace and Split on a separator; both return a slice of strings (a list you will meet in chapter 3), and strings.Join glues such a list back together.
Formatting with fmt.Printf and fmt.Sprintf
fmt.Printf prints formatted text and fmt.Sprintf returns it as a string. The format string contains verbs that are replaced, in order, by the following arguments:
package main
import "fmt"
func main() {
name, level, hp := "Gopher", 7, 82.5
fmt.Printf("%s is level %d\n", name, level)
fmt.Printf("HP %.2f or %f\n", hp, hp)
fmt.Printf("%v %v %v\n", name, level, hp)
fmt.Printf("%q %t\n", name, level > 5)
fmt.Printf("[%5d] [%-8s] [%02d]\n", level, name, level)
msg := fmt.Sprintf("%s has %d gold", name, 120)
fmt.Println(msg)
}
Gopher is level 7
HP 82.50 or 82.500000
Gopher 7 82.5
"Gopher" true
[ 7] [Gopher ] [07]
Gopher has 120 gold
%sstrings,%dintegers,%tbooleans,%vany value in its default format.%ffloats with six decimals;%.2fwith two.%qa string in double quotes — handy for spotting stray spaces.- A width between
%and the verb pads the value:%5dright-aligns in five columns,%-8sleft-aligns in eight, and%02dpads with zeros. %%prints a literal percent sign.
Unlike Println, Printf adds no newline: end the format with \n.
Numbers to strings
+ only joins strings, so "Level " + level doesn't compile when level is an int. Convert the number with strconv.Itoa ("integer to ASCII") from the strconv package, or use fmt.Sprintf:
label := "Level " + strconv.Itoa(level)
Don't use string(level): it converts a number to the character with that code, so string(rune(65)) is "A", not "65".
Common mistakes
- Counting characters with
len: it counts bytes, so non-ASCII text looks longer than it is. - Treating
s[0]as a string: it is a byte. Uses[:1]for a one-byte substring. - Slicing past the end:
s[:10]on a shorter string panics at run time. - A verb that doesn't fit:
%dwith a string prints%!d(string=Gopher)instead of failing loudly.
Assignment
The function skeletons are given — put your code where the TODO comments are and use return. The starter only imports fmt; add "strings" to the import block when you need it.
FormatPrice(item string, cents int) stringreturns the item and its price in dollars, always with two digits for the cents:FormatPrice("Sword", 1250)is"Sword: $12.50"andFormatPrice("Potion", 5)is"Potion: $0.05".centsis never negative.Initials(first, last string) stringreturns the upper-case first letter of each name, each followed by a dot:Initials("rob", "pike")is"R.P.". Both names are non-empty and contain only ASCII letters.Shout(s string) stringremoves leading and trailing whitespace, converts the text to upper case and adds an exclamation mark:Shout(" hello gopher ")is"HELLO GOPHER!".
Strings and formatting in other languages
- JavaScript Strings and Template Literals · JavaScript
- Python Strings and f-Strings · Python
- Java Strings and String Methods · Java
- C# Strings and String Interpolation · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .