Golang等价于Python使用F-strings对String进行了简化

e0uiprwp  于 2023-11-14  发布在  Go
关注(0)|答案(3)|浏览(106)

在python中,可以使用f-string来格式化字符串,如下所示:

name1 = 'Ele'
name2 = 'Ben'
name3 = 'Frank'
age = 45

print(f"My name is {name1} but i also get called {name2} and at times {name3}. Generally I prefer {name1} and my age is {age}")

字符串
golang的等价物是什么?我可以精确地指定哪个变量在哪个位置
目前,这是我在golang中看到的所有内容,但它创建了不必要的重复变量,如下所示

name1 := "Ele"
name2 := "Ben"
name3 := "Frank"
age := 45

message := fmt.Sprintf("My name is %s but i also get called %s and at times %s. Generally I prefer %s and my age is %d", name1, name2, name3, name1, age)

fmt.Println(message)


想象一下,如果我需要在同一个字符串中多次重复一个变量,我将不得不不断重复它,然后需要始终监视变量的位置,以确保它们正确对齐
有没有类似python中f-string的方法来处理golang?

a64a0gku

a64a0gku1#

可以使用text/template
对于这个简单的例子来说,这有点过头了,但是当处理复杂的模板、大量的输出等时,这是值得的。

package main

import (
    "bytes"
    "fmt"
    "log"
    "text/template"
)

func main() {
    data := fdata{
        "Name1": "Ele",
        "Name2": "Ben",
        "Name3": "Frank",
        "Age":   45,
    }
    format := "My name is {{.Name1}} but I also get called {{.Name2}} and at times {{.Name3}}. Generally I prefer {{.Name1}} and my age is {{.Age}}."

    result, err := fstring(format, data)
    if err != nil {
        log.Fatalf("fstring() failed: %v", err)
    }

    fmt.Println(result)
}

type fdata map[string]interface{}

func fstring(format string, data fdata) (string, error) {
    t, err := template.New("fstring").Parse(format)
    if err != nil {
        return "", fmt.Errorf("error creating template: %v", err)
    }
    output := new(bytes.Buffer)
    if err := t.Execute(output, data); err != nil {
        return "", fmt.Errorf("error executing template: %v", err)
    }
    return output.String(), nil
}

字符串
输出量:

My name is Ele but I also get called Ben and at times Frank. Generally I prefer Ele and my age is 45.


Go Playground

uajslkp6

uajslkp62#

# Prints today's date with help
# of datetime library

import datetime
 

today = datetime.datetime.today()

print(f"{today:%B %d, %Y}")

字符串
输出量:

April 04, 2018


注意:F字符串比两种最常用的字符串格式化机制(%化和str.format())更快。
让我们看看一些错误的例子,这可能会发生在使用f字符串:

lf5gs5x2

lf5gs5x23#

我已经使用fmt.Println("My name is " + name),我已经声明了var name prior作为我的名字,它工作了。但是我试着做fmt.Print("My name is " + name "and my age is" + age),这会产生一个错误
编辑:我得到了这个,因为在go lang中,你不能使用int和string,所以你必须写为:

package main

import "fmt"

func main() {
    //var name string = "Srijit"
    var name string = "Srijit"
    fmt.Println("My name is " + name)
    name = "Sam"
    fmt.Println("My name is " + name)

    num := 23

    fmt.Println("My name is "+name, "and my age is", num)
}

字符串
我把+num改成了,num(它不允许string变成num)

相关问题