Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
Problem :
You want to print rune, unicode or CJK(Chinese/Japanese/Korean) characters with Golang, but you are getting funny result. How to print rune properly?
Solution :
Use quoted verb in your Printf statement. From https://blog.golang.org/strings :
"The %q (quoted) verb will escape any non-printable byte sequences in a string so the output is unambiguous."
For example :
package main
import (
"fmt"
)
func main() {
sr := '\u212A'
fmt.Println(sr) // wrong way to print!
fmt.Printf("%+q\n", sr) // print back the unicode
fmt.Printf("%q\n", sr) // print K (Kelvin symbol)
src := '你'
fmt.Printf("%q\n", src) // print character 你
fmt.Printf("%+q\n", src) // print unicode codepoint
}
Output :
8490
'\u212a'
'K'
'你'
'\u4f60'
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.3k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+18.4k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+19.3k Golang : Saving private and public key to files
+8.5k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+7.1k Golang : Append and add item in slice
+12.6k Golang : Check if an integer is negative or positive
+34.4k Golang : Validate IP address
+19.8k Golang : How to read float value from standard input ?
+25.1k Golang : Convert file content into array of bytes
+12.6k Golang : unknown escape sequence error
+3.6k Java : Generate multiplication table example
+31.6k Golang : Smarter Error Handling with strings.Contains()