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
+20.4k Golang : Count number of digits from given integer value
+32.3k Golang : Convert an image file to []byte
+10.5k Golang : Embed secret text string into binary(executable) file
+14k Golang : Image to ASCII art example
+7.5k Golang : File system scanning
+9.3k Golang : Simple histogram example
+9.5k Golang : How to get garbage collection data?
+7.2k Golang : Takes a plural word and makes it singular
+5.3k Swift : Convert (cast) Float to Int or Int32 value
+18.7k Golang : Logging with logrus
+11.5k Golang : How to use if, eq and print properly in html template
+8.5k Golang : Find relative luminance or color brightness