search
HomeBackend DevelopmentGolangAbout Golang string formatting

About Golang string formatting

Oct 12, 2020 pm 02:12 PM
gogolang

Below, I will introduce you to Golang string formatting by # Section of # Section. I hope it will be helpful to friends who need it!

About Golang string formatting

golang format

In Go language, fmt.Sprintf(), fmt.Printf( ), fmt.Fprintf(), Log.Printf(), log.Panicf() and other functions often use string formatting parameters. This article will familiarize you with all parameters.

Parameter introduction

##%UUnicode characters%fFloating point number%pPointer, hexadecimal display
Verb Function
%v Output the original value of the value
% v in %v Basically, expand the structure field names and values
%#v Output the value in Go language syntax format
%T Output the type and value of Go language syntax format
%% Output % ontology
%b The integer type is displayed in binary format
%o The integer type is displayed in octal format
%d The integer type is displayed in decimal format
%x The integer type is displayed in hexadecimal format
%X Integers are displayed in hexadecimal and uppercase letters

Practical example

package mainimport "fmt"import "os"type point struct {
    x, y int}func main() {

    // Go 为常规 Go 值的格式化设计提供了多种打印方式。例
    // 如,这里打印了 `point` 结构体的一个实例。
    p := point{1, 2}
    fmt.Printf("%v\n", p)
    // 输出:{1 2}

    // 如果值是一个结构体,`%+v` 的格式化输出内容将包括
    // 结构体的字段名。
    fmt.Printf("%+v\n", p)
    // 输出:{x:1 y:2}

    // `%#v` 形式则输出这个值的 Go 语法表示。例如,值的
    // 运行源代码片段。
    fmt.Printf("%#v\n", p)
    // 输出:main.point{x:1, y:2}

    // 需要打印值的类型,使用 `%T`。
    fmt.Printf("%T\n", p)
    // 输出:main.point

    // 格式化布尔值是简单的。
    fmt.Printf("%t\n", true)
    // 输出:true

    // 格式化整形数有多种方式,使用 `%d`进行标准的十进
    // 制格式化。
    fmt.Printf("%d\n", 123)
    // 输出:123

    // 这个输出二进制表示形式。
    fmt.Printf("%b\n", 14)
    // 输出:1110

    // 这个输出给定整数的对应字符。
    fmt.Printf("%c\n", 33)
    // 输出:!

    // `%x` 提供十六进制编码。
    fmt.Printf("%x\n", 456)
    // 输出:1c8

    // 对于浮点型同样有很多的格式化选项。使用 `%f` 进
    // 行最基本的十进制格式化。
    fmt.Printf("%f\n", 78.9)
    // 输出:78.900000

    // `%e` 和 `%E` 将浮点型格式化为(稍微有一点不
    // 同的)科学技科学记数法表示形式。
    fmt.Printf("%e\n", 123400000.0)
    // 输出:1.234000e+08
    fmt.Printf("%E\n", 123400000.0)
    // 输出:1.234000E+08

    // 使用 `%s` 进行基本的字符串输出。
    fmt.Printf("%s\n", "\"string\"")
    // 输出:"string"

    // 像 Go 源代码中那样带有双引号的输出,使用 `%q`。
    fmt.Printf("%q\n", "\"string\"")
    // 输出:"\"string\""

    // 和上面的整形数一样,`%x` 输出使用 base-16 编码的字
    // 符串,每个字节使用 2 个字符表示。
    fmt.Printf("%x\n", "hex this")
    // 输出:6865782074686973

    // 要输出一个指针的值,使用 `%p`。
    fmt.Printf("%p\n", &p)
    // 输出:0x42135100

    // 当输出数字的时候,你将经常想要控制输出结果的宽度和
    // 精度,可以使用在 `%` 后面使用数字来控制输出宽度。
    // 默认结果使用右对齐并且通过空格来填充空白部分。
    fmt.Printf("|%6d|%6d|\n", 12, 345)
    // 输出:|    12|   345|

    // 你也可以指定浮点型的输出宽度,同时也可以通过 宽度.
    // 精度 的语法来指定输出的精度。
    fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
    // 输出:|  1.20|  3.45|

    // 要左对齐,使用 `-` 标志。
    fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
    // 输出:|1.20  |3.45  |

    // 你也许也想控制字符串输出时的宽度,特别是要确保他们在
    // 类表格输出时的对齐。这是基本的右对齐宽度表示。
    fmt.Printf("|%6s|%6s|\n", "foo", "b")
    // 输出:|   foo|     b|

    // 要左对齐,和数字一样,使用 `-` 标志。
    fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
    // 输出:|foo   |b     |

    // 到目前为止,我们已经看过 `Printf`了,它通过 `os.Stdout`
    // 输出格式化的字符串。`Sprintf` 则格式化并返回一个字
    // 符串而不带任何输出。
    s := fmt.Sprintf("a %s", "string")
    fmt.Println(s)
    // 输出:a string

    // 你可以使用 `Fprintf` 来格式化并输出到 `io.Writers`
    // 而不是 `os.Stdout`。
    fmt.Fprintf(os.Stderr, "an %s\n", "error")
    // 输出:an error}
    Result
  • {1 2}
    {x:1 y:2}
    main.point{x:1, y:2}
    main.point
    true
    123
    1110
    !
    1c8
    78.900000
    1.234000e+08
    1.234000E+08
    "string"
    "\"string\""
    6865782074686973
    0xc000100010
    |    12|   345|
    |  1.20|  3.45|
    |1.20  |3.45  |
    |   foo|     b|
    |foo   |b     |
    a string
    an error

The above is the detailed content of About Golang string formatting. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Choosing Between Golang and Python: The Right Fit for Your ProjectChoosing Between Golang and Python: The Right Fit for Your ProjectApr 19, 2025 am 12:21 AM

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang: Concurrency and Performance in ActionGolang: Concurrency and Performance in ActionApr 19, 2025 am 12:20 AM

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang vs. Python: Which Language Should You Learn?Golang vs. Python: Which Language Should You Learn?Apr 19, 2025 am 12:20 AM

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang vs. Python: Performance and ScalabilityGolang vs. Python: Performance and ScalabilityApr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Other Languages: A ComparisonGolang vs. Other Languages: A ComparisonApr 19, 2025 am 12:11 AM

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

Golang and Python: Understanding the DifferencesGolang and Python: Understanding the DifferencesApr 18, 2025 am 12:21 AM

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang vs. C  : Assessing the Speed DifferenceGolang vs. C : Assessing the Speed DifferenceApr 18, 2025 am 12:20 AM

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang: A Key Language for Cloud Computing and DevOpsGolang: A Key Language for Cloud Computing and DevOpsApr 18, 2025 am 12:18 AM

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool