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

huangapple go评论85阅读模式
英文:

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

问题

在Golang中,将字符串转换为UTF-8的方式与Python中使用str.encode('utf8')类似。你可以使用[]byte类型来表示UTF-8字节序列。

在Golang中,字符串默认使用UTF-8编码,所以当你将文本存储为Go字符串时,编码已经被处理好了,你无需额外操作。

如果你需要将字符串转换为UTF-8字节序列,你可以使用[]byte类型的强制类型转换来实现。例如:

str := "你好"
utf8Bytes := []byte(str)

这样,utf8Bytes就是str的UTF-8字节序列表示。

希望对你有所帮助!如果还有其他问题,请随时提问。

英文:

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.

答案1

得分: 18

在Python中,str.encode('utf8')将字符串转换为字节。在Go语言中,字符串已经是UTF-8编码的,如果你需要字节,可以使用[]byte(str)

英文:

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).

答案2

得分: 0

由于Go已经对字符串进行了编码,为了以类似Python文本的形式显示它,可以使用以下代码:

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

翻译结果:

fmt.Printf("%q\n", "字符串");
英文:

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

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

huangapple
  • 本文由 发表于 2017年3月2日 04:21:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/42541297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定