Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Go, is there similar feature like "f-string" in Python? [duplicate]

Tags:

go

In Go, is there a similar feature like "f-string" in Python? I cannot find a simple solution like f-string.

#Python
name = 'AlphaGo'
print(f'I am {name}') ##I am AlphaGo

A best alternative solution I found on the web and from comment is

//Golang
package main

import (
    "fmt"
)

func main() {
    const name, age = "Kim", 22
    fmt.Println(name, "is", age, "years old.") // Kim is 22 years old.
}

But, this is still not as simple as f-string...

like image 1000
hyukkyulee Avatar asked Nov 28 '19 06:11

hyukkyulee


People also ask

Does Python have F-strings?

Python f-string is the newest Python syntax to do string formatting. It is available since Python 3.6. Python f-strings provide a faster, more readable, more concise, and less error prone way of formatting strings in Python. The f-strings have the f prefix and use {} brackets to evaluate values.

What is the difference between F-string and string in Python?

There is no difference at all. See the definition of Formatted string literals in the Python documentation. A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. No further mention is made of the specific character used to introduce the literal.

Can you nest F-strings in Python?

Nested F-StringsYou can embed f-strings inside f-strings for tricky formatting problems like adding a dollar sign to a right aligned float, as shown above.

How do I create a multi line F-string in Python?

Multiline f-strings are similar to using single line f-strings in Python. It's just that the string should be mentioned within the parenthesis, i.e., the curly braces. Also, every line containing the f-string should be started with an f .


1 Answers

  1. Simply use:
fmt.Printf("I am %s\n", name) // I am AlphaGo

  1. Exported Name, use struct:
    t := template.Must(template.New("my").Parse("I am {{.Name}}\n"))
    t.Execute(os.Stdout, struct{ Name string }{name}) // I am AlphaGo

  1. Lower case name, use 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. Use .:
    t3 := template.Must(template.New("my").Parse("I am {{.}}\n"))
    t3.Execute(os.Stdout, name) // I am AlphaGo

All:

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
}
like image 151
wasmup Avatar answered Oct 06 '22 13:10

wasmup