Home > Article > Backend Development > How do I Print a Literal Percentage Symbol Using fmt.Printf in Go?
Escaping Variables with Printf for Precision
When utilizing fmt.Printf to format output, one may encounter instances where a literal percentage symbol (%) is desired within the formatted string. To achieve this and prevent its interpretation as a formatting directive, it's essential to escape the percentage character.
Escaping the First Occurrence of %v
To escape the first occurrence of %v within the format string, you cannot simply prefix it with abackslash (), as %v will still be interpreted as a formatting directive.
Solution: Using %%
The correct method to escape a literal % is to use %%. This sequence literally prints a percentage sign and consumes no value.
Example:
To escape the first %v and allow the second %v to be treated as a formatting directive, use the following code:
fmt.Printf("Escape this -> %%v... Do not escape this -> %v", "Unescaped")
This will produce the output:
Escape this -> %v... Do not escape this -> Unescaped
Additional Notes:
For further reference, please refer to the fmt package documentation for a comprehensive list of escape sequences:
https://golang.org/pkg/fmt/
The above is the detailed content of How do I Print a Literal Percentage Symbol Using fmt.Printf in Go?. For more information, please follow other related articles on the PHP Chinese website!