登录
首页 >  Golang >  Go问答

在 Go 中,Python 中是否有类似“f-string”的功能?

来源:stackoverflow

时间:2024-04-02 15:45:33 414浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《在 Go 中,Python 中是否有类似“f-string”的功能?》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

在围棋中, 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那么简单......


解决方案


在 go 中,没有与 python 中的 f 字符串直接等效的东西。但是,有一些选择:

  1. 只需使用:
fmt.printf("i am %s\n", name) // i am alphago
  1. 导出的 name,使用 struct
t := template.must(template.new("my").parse("i am {{.name}}\n"))
    t.execute(os.stdout, struct{ name string }{name}) // i am alphago
  1. 小写 name,使用 map
t2 := template.must(template.new("my").parse("i am {{.name}}\n"))
    t2.execute(os.stdout, map[string]string{"name": name}) // i am alphago
  1. 使用 .
t3 := template.must(template.new("my").parse("i am {{.}}\n"))
    t3.execute(os.stdout, name) // i am alphago

全部 - 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").Parse("I am {{.Name}}\n"))
    t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo

    t2 := template.Must(template.New("my").Parse("I am {{.name}}\n"))
    t2.Execute(os.Stdout, map[string]string{"name": name}) // I am AlphaGo

    t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
    t3.Execute(os.Stdout, name) // I am AlphaGo
}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《在 Go 中,Python 中是否有类似“f-string”的功能?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>