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.
You need to escape the %'s in format string using another %:
value := fmt.Sprintf("%%%s%%",mystring)
Use %% in your format string for an actual %.
For example:
func main() {
mystring := "hello"
value := fmt.Sprintf("%%%s%%", mystring)
fmt.Println(value)
}
Prints: %hello%
This is clearly documented at the beginning of the docs for fmt:
%% a literal percent sign; consumes no value
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