在 Go 中,Python 中是否有类似的“f-string”功能?我找不到像 f-string 这样的简单解决方案。
#Python
name = 'AlphaGo'
print(f'I am {name}') ##I am AlphaGo
我在网上和评论中找到的最佳替代解决方案是
//Golang
package main
import (
"fmt"
)
func main() {
const name, age = "Kim", 22
fmt.Println(name, "is", age, "years old.") // Kim is 22 years old.
}
但是,这仍然不像 f-string 那么简单...
只需使用:
fmt.Printf("I am %s\n", name) // I am AlphaGo
ExportedName
,usestruct
:
t := template.Must(template.New("my").P("I am {{.Name}}\n"))
t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo
Lower casename
,usemap
:
t2 := template.Must(template.New("my").P("I am {{.name}}\n"))
t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo
Use.
:
t3 := template.Must(template.New("my").P("I am {{.}}\n"))
t3.Execute(os.Stdout, name) // I am AlphaGo
All-try it on The Go Playground:
package main
import (
"fmt"
"os"
"text/template"
)
func main() {
name := "AlphaGo"
fmt.Printf("I am %s\n", name)
t := template.Must(template.New("my").P("I am {{.Name}}\n"))
t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo
t2 := template.Must(template.New("my").P("I am {{.name}}\n"))
t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo
t3 := template.Must(template.New("my").P("I am {{.}}\n"))
t3.Execute(os.Stdout, name) // I am AlphaGo
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(35条)