Format a Go string without printing?

golang string interpolation
golang string concatenation
golang print map
golang print table format
golang format time
golang print to console
golang int to string
golang format float

Is there a simple way to format a string in Go without printing the string?

I can do:

bar := "bar"
fmt.Printf("foo: %s", bar)

But I want the formatted string returned rather than printed so I can manipulate it further.

I could also do something like:

s := "foo: " + bar

But this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like

i := 25
s := "foo: " + strconv.Itoa(i)

Is there a simpler way to do this?

Sprintf is what you are looking for.

Example

fmt.Sprintf("foo: %s", bar)

You can also see it in use in the Errors example as part of "A Tour of Go."

return fmt.Sprintf("at %v, %s", e.When, e.What)

String Formatting, So far we've seen Printf , which prints the formatted string to os.Stdout . Sprintf formats and returns a string without printing it anywhere. s := fmt  Go: Format a string without printing it The fmt.Sprintf function formats a string in the same way as fmt.Printf , but returns the string instead of printing it. s := fmt.Sprintf( "Size: %d MB." , 85) fmt.Println(s) // Output: Size: 85 MB.

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if ne $i 0}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

Go: Format a string without printing it, Go: Format a string without printing it. The fmt.Sprintf function formats a string in the same way as fmt.Printf , but returns the string instead of printing it. s := fmt. To double-quote strings as in Go source, use %q. As with integers seen earlier, %x renders the string in base-16, with two output characters per byte of input. To print a representation of a pointer, use %p. When formatting numbers you will often want to control the width and precision of the resulting figure.

In your case, you need to use Sprintf() for format string.

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)

Your output will be :

Good Morning, This is John and I'm living here from last 20 years.

fmt, Use fmt.Sprintf to format a string without printing it: s := fmt.Sprintf("Binary: %b\\%b​", 4, 5) // s == `Binary: 100\101` Passing multiple string arguments to a variadic function. The parameter s accepts an infinite number of arguments. The tree-dotted ellipsis tells the compiler that this string will accept, from zero to multiple values.

fmt.SprintF function returns a string and you can format the string the very same way you would have with fmt.PrintF

fmt.Printf formatting tutorial and cheat sheet · YourBasic Go, Printing something to the standard output in Go is very easy. the adjacent argument is not a string and writes to the standard output without a trailing newline. Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print. type Stringer interface { String() string}

String formatting in Go - RunGo, Is there a simple way to format a string in Go without printing the string? I can do: bar := "bar" fmt.Printf("foo: %s", bar). But I want the formatted  Get started with the String.Format method. Use String.Format if you need to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a Decimal value into a string to display it to the user as a single string: Decimal pricePerOunce =

Format a Go string without printing?, dynamically. String formatting makes our lives easier by allowing us to do things that can take m. It is a way to create a formatted string without printing. Whenever we print list in Python, we generally use str (list) because of which we have single quotes in the output list. Suppose if the problem requires to print solution without quotes. Let’s see some ways to print list without quotes. Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you

String formatting in GoLang, Without escape characters, you would not be able to construct the string Sammy says, "I like to use the `fmt` package" . Multiple Lines. Printing  PyFormat Using % and .format() for great good! Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.

Comments
  • does letter after % matter? Could it be %y and %q ? or %y and %y
  • The letter does matter, it's called a verb, basically it lets Sprintf know what type the variable is so that if it receives 65 and the verb is %d it will print the number 65 but if the verb is %c it will print the character 'A'. See: golang.org/pkg/fmt/#hdr-Printing