英文:
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");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论