How to print string with double quotes in Golang?

Whenever the user wants to double-quote a string, he can’t simply write the string within double quotes inside the fmt.Printf() command. This prints only the text written inside those quotes. To print the string along with quotes, he can use various methods including certain escape characters. There are different ways in Golang to print a string with double-quotes.

1) Quoting a string using %q:

Syntax:

fmt.Printf("%q", output)
filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
func main() {
    var result = "Welcome to GeeksforGeeks."
    fmt.Printf("%q", result)
}

chevron_right


Output:

"Welcome to GeeksforGeeks."

Explanation: In the above example, we used “%q” to display our string with double-quotes.

2) Quoting a string using an escape character “\”:

Syntax:

fmt.Println("\"string\"")
filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
func main() {
    fmt.Println("\"GeeksforGeeks is a computer science portal\"")
}

chevron_right


Output:

"GeeksforGeeks is a computer science portal"

Explanation: In the above example, we used an escape character “\” to print a string with double-quotes. We can simply do so by adding a backslash(\) before the double-quotes.

3) Double quoting a string using a raw string lateral (`):

Syntax:

fmt.Println(`"string\"`)
filter_none

edit
close

play_arrow

link
brightness_4
code

package main
  
import "fmt"
  
func main() {
    fmt.Println(`"GeeksforGeeks"`)
}

chevron_right


Output:

"GeeksforGeeks"

Explanation: In the above example, we used a raw string lateral (`) to print a string with double-quotes.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.