String Formatting in Go
Table of Contents
Go follows the printf tradition from the C language. In my opinion, string formatting/interpolation in Go is less elegant than Python's f-strings, unfortunately.
All the content from our Boot.dev courses are available for free here on the blog. This one is the "Constants and Formatting" chapter of Learn Go. If you want to try the far more immersive version of the course, do check it out!
fmt.Printf and fmt.Sprintf
- fmt.Printf() - Prints a formatted string to standard out.
- fmt.Sprintf() - Returns the formatted string
Both follow the printf tradition: "formatting verbs" like %v and %d control how each value is rendered.
Default Representation
The %v variant prints any value in a default format. It can be used as a catchall.
s := fmt.Sprintf("I am %v years old", 10)
// I am 10 years old
s := fmt.Sprintf("I am %v years old", "way too many")
// I am way too many years old
fmt.Sprintf is a string interpolation function, similar to Python's f-strings. The %v substring uses the type's default formatting, which is often what you want.
const name = "Kim"
const age = 22
s := fmt.Sprintf("%v is %v years old.", name, age)
// s = "Kim is 22 years old."
The equivalent Python code:
name = "Kim"
age = 22
s = f"{name} is {age} years old."
# s = "Kim is 22 years old."
If you want to print in a more specific way, you can use the following formatting verbs:
String
s := fmt.Sprintf("I am %s years old", "way too many")
// I am way too many years old
Integer
s := fmt.Sprintf("I am %d years old", 10)
// I am 10 years old
Float
s := fmt.Sprintf("I am %f years old", 10.523)
// I am 10.523000 years old
// The ".2" rounds the number to 2 decimal places
s := fmt.Sprintf("I am %.2f years old", 10.523)
// I am 10.52 years old
Boolean
The %t verb formats a boolean value.
s := fmt.Sprintf("Is Go fun? %t", true)
// Is Go fun? true
If you're interested in all the formatting options, you can look at the fmt package's docs.
Frequently Asked Questions
What is the difference between fmt.Printf and fmt.Sprintf?
fmt.Printf prints a formatted string to standard output, while fmt.Sprintf returns the formatted string.
What does %v mean in Go string formatting?
%v prints any value in a default format. It can be used as a catchall.
Which verbs format strings, integers, and booleans in Go?
%s formats a string, %d formats an integer, and %t formats a boolean value.
How do you format a float to two decimal places in Go?
Use %.2f. The .2 rounds the number to two decimal places.
