python - 相当于 Go 中的 Python string.format?

标签 python string go

在 Python 中,你可以这样做:

"File {file} had error {error}".format(file=myfile, error=err)

或者这个:

"File %(file)s had error %(error)s" % {"file": myfile, "error": err}

在 Go 中,最简单的选择是:

fmt.Sprintf("File %s had error %s", myfile, err)

这不允许您交换格式字符串中参数的顺序,您需要为 I18N 执行此操作. Go 确实template包,它需要像这样的东西:

package main

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

func main() {
    type Params struct {
        File string
        Error string
    }

    var msg bytes.Buffer

    params := &Params{
        File: "abc",
        Error: "def",
    }

    tmpl, _ := template.New("errmsg").Parse("File {{.File}} has error {{.Error}}")
    tmpl.Execute(&msg, params)
    msg.WriteTo(os.Stdout)
}

这似乎是一条错误消息的漫长道路。是否有更合理的选项允许我提供独立于顺序的字符串参数?

最佳答案

使用strings.Replacer

使用 strings.Replacer ,实现您想要的格式化程序非常简单和紧凑。

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

输出(在 Go Playground 上尝试):

File /data/test.txt had error file not found

我们可以通过在 log() 函数中自动将括号添加到参数名称来使其更易于使用:

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

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

func log2(format string, args ...string) {
    for i, v := range args {
        if i%2 == 0 {
            args[i] = "{" + v + "}"
        }
    }
    r := strings.NewReplacer(args...)
    fmt.Println(r.Replace(format))
}

输出(在 Go Playground 上尝试):

File /data/test.txt had error file not found

是的,您可以说这只接受 string 参数值。这是真的。稍微改进一下,这就不是真的了:

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

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

func log3(format string, args ...interface{}) {
    args2 := make([]string, len(args))
    for i, v := range args {
        if i%2 == 0 {
            args2[i] = fmt.Sprintf("{%v}", v)
        } else {
            args2[i] = fmt.Sprint(v)
        }
    }
    r := strings.NewReplacer(args2...)
    fmt.Println(r.Replace(format))
}

输出(在 Go Playground 上尝试):

File /data/test.txt had error 666

接受参数作为 map[string]interface{} 并将结果作为 string 返回的变体:

type P map[string]interface{}

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

    s := log33("File {file} had error {error}", P{"file": file, "error": err})
    fmt.Println(s)
}

func log33(format string, p P) string {
    args, i := make([]string, len(p)*2), 0
    for k, v := range p {
        args[i] = "{" + k + "}"
        args[i+1] = fmt.Sprint(v)
        i += 2
    }
    return strings.NewReplacer(args...).Replace(format)
}

Go Playground 上试试.

使用text/template

您的模板解决方案或提案也过于冗长。它可以写得像这样紧凑(省略错误检查):

type P map[string]interface{}

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

    log4("File {{.file}} has error {{.error}}", P{"file": file, "error": err})
}

func log4(format string, p P) {
    t := template.Must(template.New("").Parse(format))
    t.Execute(os.Stdout, p)
}

输出(在 Go Playground 上尝试):

File /data/test.txt has error 666

如果你想返回 string(而不是将它打印到标准输出),你可以这样做(在 Go Playground 上尝试):

func log5(format string, p P) string {
    b := &bytes.Buffer{}
    template.Must(template.New("").Parse(format)).Execute(b, p)
    return b.String()
}

使用显式参数索引

这已在另一个答案中提到,但要完成它,请知道可以使用任意次数的相同显式参数索引,从而导致多次替换相同的参数。在这个问题中阅读更多相关信息:Replace all variables in Sprintf with same variable

关于python - 相当于 Go 中的 Python string.format?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53975343/

相关文章:

string - Swift String.removeRange 无法编译

reactjs - 跨源请求被阻止, header Access-Control-Allow-Origin 丢失

go - Golang 扫描文本文件中的单词

python - mac osx雪豹中的pyqt安装问题

python - 计算每列的统计数据并将其添加到空数据框

python - 如何在 python 中使用 TA-Lib 的技术指标和 pandas

python - 基于 gui 的脚本,与 ajax/http 交互以进行网络抓取/抓取

c++ - STL Character Traits 的重点是什么?

c - 如何将 .txt 文件的内容打印为字符串?

postgresql - 连接到在Docker中运行的postgres时出错:pq:用户“postgres”的密码身份验证失败