DMarlon Studio

Lesson 4 · 4 of 20

Strings and Printf · Go

Join strings with + and format output in Go with fmt.Printf and fmt.Sprintf: the %s, %d, %.2f, %v and %q verbs, and column widths.

Go · Strings and Printf in DMarlon Studio: the example's code and its output in the terminal

Strings (string) are joined with +: product + " beans" gives Coffee beans. len(label) counts its length in bytes, which matches the characters as long as there are no accents or special symbols; lesson 18 explains why.

fmt.Printf prints a string with verbs that are replaced, in order, by the values that follow: %s for a string, %d for an integer and %.2f for a number with two decimals. Unlike Println, it does not end the line by itself: the \n goes at the end of the format.

%v prints any value in its natural form and %q puts a string in quotes, handy for spotting stray spaces. A number between the % and the letter sets the width: %-8s takes 8 places aligned left and %6.2f takes 6 places aligned right, so the rows line up in columns.

fmt.Sprintf takes the same as Printf but, instead of printing, it returns the string, which is kept here in receipt to use later. Finally, to print the percent sign itself you double it: %d%% gives 21%.

Code · main.go

package mainimport "fmt"func main() {	product := "Coffee"	price := 3.5	units := 4	// + joins strings; len counts their bytes.	label := product + " beans"	fmt.Println(label, "has", len(label), "characters")	// Printf fills each verb with a value, in order.	fmt.Printf("%s costs %.2f euros\n", product, price)	fmt.Printf("%d units: %.2f euros\n", units, price*float64(units))	// %v prints any value; %q adds quotes.	fmt.Printf("%v | %v | %q\n", units, price, product)	// A width lines up columns: %-8s to the left, %6.2f to the right.	fmt.Printf("%-8s|%6.2f|\n", "Tea", 2.25)	fmt.Printf("%-8s|%6.2f|\n", "Cocoa", 12.4)	fmt.Printf("%-8s|%6d|\n", "Units", units)	// Sprintf returns the text instead of printing it.	receipt := fmt.Sprintf("%dx %s = %.2f", units, product, price*float64(units))	fmt.Println("Receipt:", receipt)	fmt.Printf("VAT: %d%%\n", 21) // %% writes a percent sign}

Output · go run main.go

Coffee beans has 12 characters
Coffee costs 3.50 euros
4 units: 14.00 euros
4 | 3.5 | "Coffee"
Tea     |  2.25|
Cocoa   | 12.40|
Units   |     4|
Receipt: 4x Coffee = 14.00
VAT: 21%

Key points

  • + joins strings; len counts bytes.
  • %s string, %d integer, %.2f decimals, %v any value.
  • %-8s and %6.2f set widths to line up columns.
  • Printf needs \n at the end.
  • Sprintf returns the string instead of printing it.

Exercise

Print a receipt with three products: the name on the left in 10 places, and the quantity and price on the right; add a last line with the total, built with Sprintf.