简体   繁体   中英

Equivalent of python's encode('utf8') in golang

How can I convert a string in Golang to UTF-8 in the same way as one would use str.encode('utf8') in Python? (I am trying to translate some code from Python to Golang; the str comes from user input, and the encoding is used to calculate a hash)

As far as I understand, the Python code converts unicode text into a string. The string is a collection of UTF-8 bytes. This sounds similar to strings in Go. So is this encoding already done for me when I store some text as a Go string?

Should I walk over the string and try utf8.EncodeRune in go? I'm really confused.

In Python, str.encode('utf8') converts a string to bytes. In Go, strings are utf-8 encoded already, if you need bytes, you can do: []byte(str) .

Since go has already encoded string, still for sake of displaying it in python-like text.

fmt.Printf("%q\n", "string");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM