Jim
Jim

Reputation: 67

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.

Upvotes: 5

Views: 20126

Answers (2)

Machinexa
Machinexa

Reputation: 589

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

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

Upvotes: 0

masnun
masnun

Reputation: 11906

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

Upvotes: 19

Related Questions