How to format strings in Go

While writing Go code, you will find string formatting very useful in many situations. You may analyze the inputs or formulate more complex outputs than simple sequencing. It may work with other types than regular strings.

Go’s String format uses the familiar operation and syntax of the printf function, which is also used by languages ​​from Java to Haskell.

Go provides various ways to format strings as FMT Package. You can use functions and verbs to format the string based on the operation or input you want to format.

String format in Go

Functions in the fmt package are similar to their counterparts, such as the printf function in bash or C. Go derives its format verbs from C.

you are using String format verbs As placeholders for the variable values ​​in the containing string. You can then pass this format string to a function like Printefalong with the corresponding values ​​for those placeholders.

You cannot use string format verbs with extension printing press And the Brentline Methods. You can use it in ways like Printef And the Sprint.

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

The %Fifth The verb prints any value in its default format. The Brentline The method does not recognize verbs and prints any arguments it receives. The Printef And the Sprint Both functions format the argument of the first string you pass to them.

String format functions in the FMT package

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

The Printef 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)

Traditionally, you won’t have to worry about errors when using a file Printef method.

The Sprint method according to the specified format and return the result as a string.

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

The Fprintf The method formulates the string and writes it to a writer (methods that implement the extension io. clerk user interface)

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

The fascanv Scan method from reader and formats according to the selected format.

var take string

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

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

In this case, the file fascanv Decrypts the string from the reader to a file Takes variable and read A variable that holds the result of formatting.

String format verbs

Go provides several format verbs that you can use with string format functions.

There are general verbs to coordinate strings like %Fifth Examples of String Coordination Functions. You can use the generic string format verbs to format any data type.

You can use the %#Fifth Verb to output any value, the % + v for installations, and % T Verb for any value type, and %% An act of no value.

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 A variable that holds the formatted string of the generated struct. If you print it, it should look something like this:

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

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

verb Careers
% logical.
%Dr int, int8, etc.
%d, %#x if printing with %#v uint, uint8, etc.
% g float32, complex64, etc.
%s series.
% s Chan.
%P pointer.

You’ll want to make sure you don’t make mistakes in verbs because they are case sensitive, like chan And the pointer actions.

Format integers and floats

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

verb Careers
%B Rule 2
% c The character represented by the corresponding Unicode code point.
%Dr Rule 10.
% o Rule 8.
% s Base 8 prefixed with 0o.
%q Safely quoted single character escaped with Go syntax.
% x Base 16, lowercase for af.
%X Base 16, in capital letters for AF.
%u Unicode format: U+1234; Like “U+%04X”.

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

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

These are floating point number formatting verbs.

verb Careers
%B Decimal scientific notation with an exponent of a power of two, the strconv method. FormatFloat in “b” format, for example -123456p-78
% e Scientific notation, e.g. -1.234456e + 78
% e The decimal point but without the exponent, for example, 123.456
%F The decimal point but without the exponent, for example, 123.456
%F A synonym for %f.
% g %e for large exponents, and %f for the other cases. Res below.
% g %E for large exponents, otherwise %F
% x Hexadecimal notation (with a decimal power of an ascendant), for example, -0x1.23abcp + 20.
%X Large hexadecimal notation, for example -0X1.23ABCP + 20.

Here is an example of formatting a decimal point without the exponent with %F verb.

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

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

String and byte formatting

Strings and segments of byte types are very similar in Go. These are string and byte formatting tags.

verb Careers
%s Unexplained string or slice bytes
%q Double Quoted String Safely Dropped Using Go syntax
% x Base 16, lowercase, 2 characters per byte
%X Base 16, uppercase, 2 characters per byte

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

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

The fmt package is necessary for Python programming

The FMT The package contains most of the functionality you will need to format the string. Go also provides a file strings package for chain tampering and register Package that can format strings for recording.

The FMT The package has functions that are implemented io. clerk And the io . reader interfaces. You will find it useful for many use cases such as creating web and command line applications.

(Visited 1 times, 1 visits today)

Related posts

Leave a Comment