Open In App

How to print string with double quotes in Golang?

Improve
Improve
Like Article
Like
Save
Share
Report

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)




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


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\"")




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


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\"`)




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


Output:

"GeeksforGeeks"

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



Last Updated : 04 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads