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
+18.3k Golang : Put UTF8 text on OpenCV video capture image frame
+22.3k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+5.3k Python : Create Whois client or function example
+4.9k Javascript : How to get width and height of a div?
+12.1k Golang : Convert a rune to unicode style string \u
+11.3k Google Maps URL parameters configuration
+9.3k Golang : How to check if a string with spaces in between is numeric?
+14k Generate salted password with OpenSSL example
+9.2k Golang : Serving HTTP and Websocket from different ports in a program example
+13.7k Golang : Set image canvas or background to transparent
+19.3k Golang : Check if directory exist and create if does not exist
+16.1k Golang : Read large file with bufio.Scanner cause token too long error