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.1k Golang : How do I get the local IP (non-loopback) address ?
+6k Golang : Transform lisp or spinal case to Pascal case example
+17k Golang : Iterating Elements Over A List
+8k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+21.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+12.5k Golang : Human readable time elapsed format such as 5 days ago
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+13.5k Golang : Execute function at intervals or after some delay
+10.5k How to tell if a binary(executable) file or web application is built with Golang?
+18k Mac OSX : Homebrew and Golang
+4.9k Golang : How to search a list of records or data structures
+11.2k Golang : Extract part of string with regular expression