How to Format Strings in Go

As you write Go code, you’ll find string formatting very useful in many situations. You might be parsing inputs or crafting more complex output than simple concatenation. You might be working with types other than plain strings.

String formatting in Go uses the familiar process and syntax of the printf function, which languages from Java to Haskell also use.

Go provides various methods for formatting strings in the fmt package. You can use functions and verbs for string formatting depending on the operation or inputs you want to format.

String Formatting in Go

The functions in the fmt package are similar to counterparts, like the printf function in bash or C. Go derives its formatting verbs from C.

You use string formatting verbs as placeholders for your variable values in a containing string. You can then pass that formatting string to a function like Printf, along with values corresponding to those placeholders.

You can’t use string formatting verbs with the Print and Println methods. You can use them with methods like Printf and Sprintf.

fmt.Println("This is a test %v", 90)
fmt.Printf("This is a test %v", 90)

The %v verb prints any value in its default format. The Println method doesn’t recognize verbs and prints whatever arguments it receives. The Printf and Sprintf functions both format the first string argument you pass to them.

String Formatting Functions in the fmt Package

Formatting strings in the Go programming language requires you to use a string formatting function and a verb. The function returns the formatted string, and the verbs are the placeholders for the inputs to the string.

The Printf method formats the input according to the format specifier and returns the number of written bytes or errors.

fmt.Printf("This is a test %v", 90)

Conventionally, you won’t have to worry about errors when you use the Printf method.

The Sprintf method formats according to the specified format and returns the result as a string.

var result = fmt.Sprintf("This is a test %v", 90)

The Fprintf method formats the string and writes it to a writer (methods that implement the io.Writer interface)

result, err = fmt.Fprintf(writer, "This is a test %v", 90)

The Fscanf method scans from a reader and formats according to the specified format.

var take string

readString := strings.NewReader("This is a test")

read, err := fmt.Fscanf(reader, "%v", &take)

In this case, the Fscanf decodes the string from the reader into the take variable, and the read variable holds the result of the format.

The String Formatting Verbs

Go provides many formatting verbs that you can use along with the string formatting functions.

There are general string formatting verbs like the %v verb in the string formatting functions examples. You can use the general string formatting verbs to format any data type.

You can use the %#v verb to output any value, the %+v for structs, the %T verb for the type of any value, and the %% verb for no values.

type any struct { 
name string
age int
isLoggedIn bool

var instance = any {
name: "John Doe",
age: 34,
isLoggedIn: true,

var result = fmt.Sprintf("This is a struct formatting example %+v", instance)

The result variable holds the formatted string of the instantiated struct. If you print it out, it should look something like this:

This is a struct formatting example {name:John Doe age:34 isLoggedIn:true}

There are the verbs for formatting specific Go native data types, including channels and pointers.

Verb Functionality
%t booleans.
%d int, int8, etc.
%d, %#x if printed with %#v uint, uint8, etc.
%g float32, complex64, etc.
%s string.
%p chan.
%P pointer.

You’ll want to ensure that you don’t make mistakes with the verbs since they are case-sensitive, like the chan and pointer verbs.

Formatting Integers and Floats

There are string formatting verbs for formatting integers in different bases. You can use any of these verbs to format integers

Verb Functionality
%b base 2
%c the character represented by the corresponding Unicode code point.
%d base 10.
%o base 8.
%O base 8 with 0o prefix.
%q a single-quoted character literal safely escaped with Go syntax.
%x base 16, with lower-case letters for a-f.
%X base 16, with upper-case letters for A-F.
%U Unicode format: U+1234; same as “U+%04X”.

For example, you can format an integer using the %d verb:

var result = fmt.Sprintf("This is an integer formatting example %d", 90)

These are the verbs for formatting floating point numbers.

Verb Functionality
%b decimalless scientific notation with exponent a power of two, in the manner of strconv. FormatFloat with the ‘b’ format, e.g. -123456p-78
%e scientific notation, e.g. -1.234456e+78
%E decimal point but no exponent, e.g., 123.456
%f decimal point but no exponent, e.g., 123.456
%F synonym for %f.
%g %e for large exponents, %f otherwise. Precision below.
%G %E for large exponents, %F otherwise
%x hexadecimal notation (with decimal power of two exponents), e.g., -0x1.23abcp+20.
%X upper-case hexadecimal notation, e.g. -0X1.23ABCP+20.

Here’s an example of formatting a decimal point without exponent with the %f verb.

var result = fmt.Sprintf("This is a floating point formatting example %f", 432.9503)

You can always use the general verbs if you’re uncertain about the type.

Formatting Strings and Bytes

Strings and slice of byte types are pretty similar in Go. These are the flags for formatting strings and bytes.

Verb Functionality
%s the uninterpreted bytes of the string or slice
%q a double-quoted string safely escaped with Go syntax
%x base 16, lower-case, two characters per byte
%X base 16, upper-case, two characters per byte

Here’s an example of formatting a string with the %s verb.

var score = "example"
var result = fmt.Sprintf("This is a string formatting example %s", score)

The fmt Package Is Essential for Python Programming

The fmt package contains most of the functionality you’ll need for string formatting. Go also provides a strings package for string manipulation and a log package that can format strings for logging.

The fmt package has functions that implement the io.Writer and io.Reader interfaces. You’ll find it useful for many use cases like building web and command line applications.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button