banner
biuaxia

biuaxia

"万物皆有裂痕,那是光进来的地方。"
github
bilibili
tg_channel

Printf formatted output

title: Printf Formatted Output
date: 2022-06-19 21:01:00
toc: false
index_img: http://api.btstu.cn/sjbz/?lx=m_dongman&cid=6
category:

  • Go
    tags:
  • Read
  • Order
  • Support
  • Format
  • Output
  • Text
  • String
  • Different
  • Print
  • Method
  • Pointer
  • Function

Print, Println, Printf, Sprintf, and Fprintf are all common methods in the fmt package, used when printing information. What are the differences between these functions?

Print: Outputs to the console (does not accept any formatting, equivalent to applying %v to each operand)  
fmt.Print(str)  
Println: Outputs to the console and adds a newline  
fmt.Println(tmp)  
Printf: Can only print formatted strings. Can only directly output string type variables (cannot output integer variables and integers, etc.)  
fmt.Printf("%d", a)  
Sprintf: Formats and returns a string without any output.  
s := fmt.Sprintf("a %s", "string") fmt.Printf(s)  
Fprintf: Formats and outputs to io.Writers instead of os.Stdout.  
fmt.Fprintf(os.Stderr, "an %s\n", "error")  

Printf Formatted Output#

General Placeholders:#

v     Default format of the value.  
%+v   Adds field names (like structs)  
%#v   Go syntax representation of the corresponding value  
%T    Go syntax representation of the type of the corresponding value  
%%    Literal percent sign, not a placeholder for a value  

Boolean Values:#

%t   true or false  

Integer Values:#

%b     Binary representation  
%c     Character represented by the corresponding Unicode code point  
%d     Decimal representation  
%o     Octal representation  
%q     Character literal surrounded by single quotes, safely escaped by Go syntax  
%x     Hexadecimal representation, letters in lowercase a-f  
%X     Hexadecimal representation, letters in uppercase A-F  
%U     Unicode format: U+1234, equivalent to "U+%04X"  

Floating Point and Complex Numbers:#

%b     Scientific notation with no decimal part, exponent as a power of two, consistent with 'b' conversion format in strconv.FormatFloat. For example, -123456p-78  
%e     Scientific notation, for example, -1234.456e+78  
%E     Scientific notation, for example, -1234.456E+78  
%f     Decimal representation with a decimal point and no exponent, for example, 123.456  
%g     Chooses %e or %f based on the situation to produce more compact (no trailing 0) output  
%G     Chooses %E or %f based on the situation to produce more compact (no trailing 0) output  

String and Bytes Slice Representation:#

%s     Uninterpreted bytes of a string or slice  
%q     String surrounded by double quotes, safely escaped by Go syntax  
%x     Hexadecimal, lowercase letters, two characters per byte  
%X     Hexadecimal, uppercase letters, two characters per byte  

Pointers:#

%p     Hexadecimal representation, prefixed with 0x  

There is no 'u' flag here. If the integer is of an unsigned type, it will be printed as unsigned. Similarly, there is no need to specify the size of the operand (int8, int64).

The default format for %v is:#

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

From this, it can be seen that the default output format can be specified using %v, unless outputting a format different from the default, %v can be used as a substitute.

For Composite Objects:#

The elements inside are printed using the following rules:

struct:            {field0 field1 ...}  
array, slice:      [elem0 elem1 ...]  
maps:              map[key1:value1 key2:value2]  
pointer to above:  &{}, &[], &map[]  

Width and Precision:#

Width is the value after %, if not specified, the default value of that value is used. Precision is the value following the width, if not specified, the default precision of the value to be printed is also used. For example: %9.2f, width 9, precision 2

%f:      default width, default precision  
%9f     width 9, default precision  
%.2f     default width, precision 2  
%9.2f    width 9, precision 2  
%9.f     width 9, precision 0  

For numeric values, width is the minimum width occupied by that value; precision is the number of digits after the decimal point. But for %g/%G, precision is the total number of digits. For example, for 123.45, the format %6.2f will print 123.45, while %.4g will print 123.5. The default precision for %e and %f is 6; but for %g, its default precision is the minimum number of digits necessary to represent that value.

For most values, width is the minimum number of characters for output, and if necessary, spaces will be filled for the formatted form. For strings, precision is the maximum number of characters for output, and if necessary, it will be truncated directly.

Width refers to "the necessary minimum width." If the width of the resulting string exceeds the specified width, the specified width will be ignored.

If the width is specified as *, the width value will be taken from the parameters.

The number following the "." indicates precision (if only "." is present, it will be ".0"). If encountering integer specifiers (d', i', b', o', x', X', `u'), precision indicates the length of the numeric part.

If encountering floating-point specifiers (`f'), it indicates the number of digits in the decimal part.

If encountering floating-point specifiers (e', E', g', G'), it indicates the number of significant digits.

If precision is set to *, the precision value will be extracted from the parameters.

For strings %s or floating-point types %f, precision can truncate the length of the data. As shown below.

func main() {  
    a := 123  
    fmt.Printf("%1.2d\n", a)    //123, width 1 is less than the width of the value itself, ineffective, while precision is 2, unable to truncate integer  
    b := 1.23  
    fmt.Printf("%1.1f\n", b)    //1.2, precision is 1, truncating floating-point data  
    c := "asdf"  
    fmt.Printf("%*.*s\n", 1, 2, c) //as, using '*' to support input of width and precision, and the string can also be truncated by precision  
}  
+     Always print the sign of the numeric value; for %q (%+q) ensures only ASCII encoded characters are output.  
-     Left-align  
#     Alternate format: adds leading 0 for octal (%#o), adds leading 0x (%#x) or 0X (%#X) for hexadecimal, removes leading 0x for %p (%#p); for %q, if strconv.CanBackquote returns true, it will print the original (i.e., backquoted) string; if it is a printable character, %U (%#U) will write out the Unicode encoding of that character (for example, character x will be printed as U+0078 'x').  
' '  (space) reserves space for the omitted sign of the numeric value (% d); when printing strings or slices in hexadecimal (% x, % X), spaces are used to separate bytes.  
0     Fills leading zeros instead of spaces; for numbers, this will move the fill after the sign.  

For each Printf-like function, there is a Print function that does not accept any formatting, which is equivalent to applying %v to each operand. Another variadic function Println will insert spaces between operands and append a newline at the end.

Disregarding placeholders, if the operand is an interface value, its internal concrete value will be used, not the interface itself. As shown below:

package main  
 
import (  
    "fmt"  
)  
 
type Sample struct {  
    a   int  
    str string  
}  
 
func main() {  
    var i interface{} = Sample{1, "a"}  
    fmt.Printf("%v\n", i) // {1 a}  
}  

Display Parameter Placeholders:#

Go supports displaying parameter placeholders by specifying their output order in the output format, as shown below:

func main() {  
    fmt.Printf("%[2]d, %[1]d\n", 11, 22)  //22, 11, first outputs the second value, then the first value  
}  

Differences in Input Methods#

Scan, Scanf, and Scanln        read from os.Stdin;  
Fscan, Fscanf, and Fscanln     read from a specified io.Reader;  
Sscan, Sscanf, and Sscanln     read from the argument string.  
Scanln, Fscanln, and Sscanln   stop scanning at newline characters and require entries to immediately follow the newline;  
Scanf, Fscanf, and Sscanf      require input newline characters to match the newline characters in the format; other functions treat newline characters as spaces.  

package main  
import "fmt"  
import "os"  
type point struct {  
    x, y int  
}  
func main() {  
    // Go provides various printing methods for formatting regular Go values. For example, here we print an instance of the point struct.  
    p := point{1, 2}  
    fmt.Printf("%v\n", p) // {1 2}  
    // If the value is a struct, the output of %+v will include the field names of the struct.  
    fmt.Printf("%+v\n", p) // {x:1 y:2}  
    // %#v format outputs the Go syntax representation of this value. For example, a snippet of the source code of the value.  
    fmt.Printf("%#v\n", p) // main.point{x:1, y:2}  
    // To print the type of the value, use %T.  
    fmt.Printf("%T\n", p) // main.point  
    // Formatting boolean values is simple.  
    fmt.Printf("%t\n", true)  
    // There are many ways to format integer numbers, using %d for standard decimal formatting.  
    fmt.Printf("%d\n", 123)  
    // This outputs the binary representation.  
    fmt.Printf("%b\n", 14)  
    // This outputs the corresponding character for the given integer.  
    fmt.Printf("%c\n", 33)  
    // %x provides hexadecimal encoding.  
    fmt.Printf("%x\n", 456)  
    // There are also many formatting options for floating-point types. Use %f for the most basic decimal formatting.  
    fmt.Printf("%f\n", 78.9)  
    // %e and %E format floating-point types into (slightly different) scientific notation representations.  
    fmt.Printf("%e\n", 123400000.0)  
    fmt.Printf("%E\n", 123400000.0)  
    // Use %s for basic string output.  
    fmt.Printf("%s\n", "\"string\"")  
    // To output with double quotes like in Go source code, use %q.  
    fmt.Printf("%q\n", "\"string\"")  
    // Like the integer above, %x outputs the string using base-16 encoding, with each byte represented by 2 characters.  
    fmt.Printf("%x\n", "hex this")  
    // To output the value of a pointer, use %p.  
    fmt.Printf("%p\n", &p)  
    // When outputting numbers, you will often want to control the width and precision of the output, which can be done by using numbers after %. The default result is right-aligned and fills the blank parts with spaces.  
    fmt.Printf("|%6d|%6d|\n", 12, 345)  
    // You can also specify the output width for floating-point types, and you can specify the precision using the width.precision syntax.  
    fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)  
    // To left-align, use the - flag.  
    fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)  
    // You may also want to control the width of string output, especially to ensure they align in tabular output. This is basic right-aligned width representation.  
    fmt.Printf("|%6s|%6s|\n", "foo", "b")  
    // To left-align, use the - flag, just like with numbers.  
    fmt.Printf("|%-6s|%-6s|\n", "foo", "b")  
    // So far, we have seen Printf, which outputs formatted strings through os.Stdout. Sprintf formats and returns a string without any output.  
    s := fmt.Sprintf("a %s", "string")  
    fmt.Println(s)  
    // You can use Fprintf to format and output to io.Writers instead of os.Stdout.  
    fmt.Fprintf(os.Stderr, "an %s\n", "error")  
}  

Scanf Formatted Output#

Scanf, Fscanf, and Sscanf parse arguments based on the format string, similar to Printf. For example, %x will scan an integer as a hexadecimal number, while %v will scan the value's default representation.

Formatting is similar to Printf, but there are exceptions, as follows:

%p  Not implemented  
%T  Not implemented  
%e %E %f %F %g %G  All completely equivalent and can scan any floating-point or composite numeric value  
%s and %v     When scanning strings, spaces are treated as delimiters  
Flags # and +  Not implemented  

In input Scanf, width can be understood as the input text (e.g., %5s indicates input of 5 characters), while Scanf does not have the concept of precision (there is no %5.2f, only %5f).

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.