Search code examples
gostring-formatting

Put string between two % in Golang


I have a string in Golang called mystring and I want to put it between 2 percentage signs (like this %mystring%). However until now I wasn't able to do it.

The things that I have tried are:

value := fmt.Sprintf("%%s%",mystring)
value := fmt.Sprintf("%s%s%s","%",mystring,"%")
value := fmt.Sprintf("/% %s/%",mystring)

But when I print it, in the end I receive a nil. Example: the value of mystring is "HelloWorld" then I get: %HelloWorld%nil

Right now I am receiving this as result:

/%s/%!(NOVERB)%!(EXTRA string=HelloWorld)<nil>

So, what am I missing?
Thanks.


Solution

  • You need to escape the %'s in format string using another %:

    value := fmt.Sprintf("%%%s%%",mystring)