简体   繁体   English

相当于 python 在 golang 中的 encode('utf8')

[英]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?如何将 Golang 中的字符串转换为 UTF-8,就像在 Python 中使用str.encode('utf8')一样? (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) (我正在尝试将一些代码从 Python 翻译成 Golang;str 来自用户输入,编码用于计算哈希)

As far as I understand, the Python code converts unicode text into a string.据我了解,Python 代码将 unicode 文本转换为字符串。 The string is a collection of UTF-8 bytes.该字符串是 UTF-8 字节的集合。 This sounds similar to strings in Go. So is this encoding already done for me when I store some text as a Go string?这听起来类似于 Go 中的字符串。当我将一些文本存储为 Go 字符串时,这种编码是否已经为我完成了?

Should I walk over the string and try utf8.EncodeRune in go?我应该遍历字符串并在 go 中尝试utf8.EncodeRune吗? I'm really confused.我真的很困惑。

In Python, str.encode('utf8') converts a string to bytes. 在Python中, str.encode('utf8')将字符串转换为字节。 In Go, strings are utf-8 encoded already, if you need bytes, you can do: []byte(str) . 在Go中,字符串已经是utf-8编码,如果你需要字节,你可以这样做: []byte(str)

Since go has already encoded string, still for sake of displaying it in python-like text.由于 go 已经编码了字符串,仍然是为了以类似 python 的文本显示它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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