Home > Backend Development > Golang > How do I Print a Literal Percentage Symbol Using fmt.Printf in Go?

How do I Print a Literal Percentage Symbol Using fmt.Printf in Go?

Linda Hamilton
Release: 2024-11-24 13:41:12
Original
561 people have browsed it

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")
Copy after login

This will produce the output:

Escape this -> %v... Do not escape this -> Unescaped
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template