2018-01-05 18:43 阅读 136


I have a string in Golang called mystring and I want to put it between 2 percentages (%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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongtangyi8962 dongtangyi8962 2018-01-05 18:45

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

    value := fmt.Sprintf("%%%s%%",mystring)
    点赞 评论 复制链接分享
  • dou7466 dou7466 2018-01-05 18:45

    Use %% in your format string for an actual %.

    For example:

    func main() {
        mystring := "hello"
        value := fmt.Sprintf("%%%s%%", mystring)

    Prints: %hello%

    This is clearly documented at the beginning of the docs for fmt:

    %% a literal percent sign; consumes no value

    点赞 评论 复制链接分享