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...
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.
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.
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.
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 .
fmt.Printf("I am %s\n", name) // I am AlphaGo
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
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
.
: 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With