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
+17.4k Golang : Set, Get and List environment variables
+31.2k Golang : How to check if a date is within certain range?
+11.4k Golang : Exit, terminating or aborting a program
+18.3k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+17.6k Golang : Get host name or domain name from IP address
+9.2k Golang : Resolve domain name to IP4 and IP6 addresses.
+13.3k Golang : How to shuffle elements in array or slice?
+8.9k Golang : Setting variable value with ldflags
+4.4k Python : Delay with time.sleep() function example
+4k Google : Block or disable caching of your website content
+8.5k Golang : Format strings to SEO friendly URL example
+10k Golang : How to pipe input data to executing child process?