Home > Backend Development > Golang > Is There a Go Equivalent to Python's `string.format()`?

Is There a Go Equivalent to Python's `string.format()`?

DDD
Release: 2024-12-16 18:42:10
Original
444 people have browsed it

Is There a Go Equivalent to Python's `string.format()`?

An Equivalent of Python's string.format in Go

Python provides a convenient method called string.format for formatting strings with custom placeholders. Go developers have questioned if there is an equivalent feature in their language.

Existing Options

The simplest alternative in Go is the fmt.Sprintf function, which allows for parameter substitution in a format string. However, it doesn't support swapping the order of parameters.

Go also includes the text/template package, which offers a more versatile approach.

Alternative Solutions

Using strings.Replacer

By utilizing the strings.Replacer type, developers can easily create their own formatting function:

package main

import (
    "fmt"
    "strings"
)

func main() {
    file, err := "/data/test.txt", "file not found"

    log("File {file} had error {error}", "{file}", file, "{error}", err)
}

func log(format string, args ...string) {
    r := strings.NewReplacer(args...)
    fmt.Println(r.Replace(format))
}
Copy after login

Using text/template

The text/template package enables more customization with a slightly more verbose approach:

package main

import (
    "fmt"
    "os"
    "text/template"
)

func main() {
    file, err := "/data/test.txt", 666

    log4("File {{.file}} has error {{.error}}", map[string]interface{}{"file": file, "error": err})
}

func log4(format string, p map[string]interface{}) {
    t := template.Must(template.New("").Parse(format))
    t.Execute(os.Stdout, p)
}
Copy after login

Using Explicit Argument Indices

Go allows the use of explicit argument indices in format strings, which enables the same parameter to be substituted multiple times.

While there are differences in implementation details, Go provides alternative solutions to Python's string.format, offering both flexibility and efficiency in string formatting scenarios.

The above is the detailed content of Is There a Go Equivalent to Python's `string.format()`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template