How to Format Strings in Go

When writing Go code, you will find string formatting very useful in many situations. You may be parsing input or creating more complex output than simple concatenation. You may be working with types other than simple strings.

String formatting in Go uses the familiar printf function process and syntax used by languages ​​from Java to Haskell.

Go provides several methods for formatting strings in the fmt Package. You can use functions and verbs to format strings, depending on the operation or the 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 a placeholder for your variable values ​​in a containing string. You can then pass that formatting string to a function like pressurealong with values ​​that match those placeholders.

You cannot use string formatting verbs with To press and printing methods. You can use them with methods like pressure and sprint f.


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

That %v Verb returns each value in its default format. That printing method does not recognize verbs and emits all arguments received. That pressure and sprint f Functions both format the first string argument you pass them.

String formatting functions in fmt package

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

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

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

Conventionally, you don’t have to worry about mistakes when using the pressure Method.

That sprint f The method formats according to the specified format and returns the result as a string.

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

That Fprintf method formats the string and writes it to a writer (methods that use the io.Writer Interface)


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

That 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 character string from the reader into the take variable, and the read The variable contains the result of the format.

The string formatting verbs

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

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

You can use the… %#v Verb to output any value that %+v for structures that %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)
fmt.Println(result)

That result Variable contains the formatted string of the instantiated structure. When 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 verbs for formatting certain native Go data types, including channels and pointers.

verb functionality
%t boolean values.
%d int, int8, etc.
%d, %#x if printed with %#v uint, uint8, etc.
%G float32, complex64, etc.
%s Line.
% p Chan.
%p Pointer.

You should make sure you don’t make any mistakes with the verbs as they are case sensitive, such as Chan and pointer verbs.

Format integers and floating point numbers

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 using the Go syntax.
%x Base 16, with lowercase for af.
%X Base 16, with capital letters for AF.
%U Unicode format: U+1234; same as “U+%04X”.

For example, you can format an integer with %d Verb:

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

These are the verbs for formatting floating point numbers.

verb functionality
% b decimalless scientific notation with exponent to a power of two, in the manner of strconv. FormatFloat with the ‘b’ format, eg -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, otherwise %F
%x Hexadecimal notation (with decimal power of two exponents), eg -0x1.23abcp+20.
%X Uppercase hexadecimal notation, eg -0X1.23ABCP+20.

Here is an example of formatting a decimal point without an exponent using the %f Verb.

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

You can always use the general verbs if you are unsure of the type.

Format 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 using the Go syntax
%x Base 16, lowercase, two characters per byte
%X Base 16, uppercase, two characters per byte

Here is an example of formatting a string using the %s Verb.

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

The fmt package is essential for Python programming

That fmt Package contains most of the functions you need for string formatting. Go also offers one strings string manipulation package and a protocol Package that can format strings for logging.

That fmt Package has functions that implement the io.Writer and io.Reader interfaces. You will find it useful for many use cases like building web and command line applications.

Leave a Reply

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