Reputation: 222811
What is the equivalent of python's chr() and ord() functions in golang?
chr(97) = 'a'
ord('a') = 97
Upvotes: 22
Views: 12467
Reputation: 418377
They are supported as simple conversions:
ch := rune(97)
n := int('a')
fmt.Printf("char: %c\n", ch)
fmt.Printf("code: %d\n", n)
Output (try it on the Go Playground):
char: a
code: 97
Note: you can also convert an integer numeric value to a string
which basically interprets the integer value as the UTF-8 encoded value:
s := string(97)
fmt.Printf("text: %s\n", s) // Output: text: a
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer. Values outside the range of valid Unicode code points are converted to
"\uFFFD"
.
Upvotes: 27
Reputation: 222811
It appears that a simple uint8('a')
will produce a correct output. To convert from integer to string string(98)
will suffice:
uint8('g') // 103
string(112) // p
Upvotes: 3