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.
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.
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)) }
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) }
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!