Finding Equivalents for Python's ord() and chr() Functions in Go
Python's ord() and chr() functions offer convenient ways to convert characters into their Unicode code points and vice versa. In Go, similar functionality is provided through simple conversions.
In Go, you can convert a Unicode code point to a character using a rune type:
ch := rune(97)
This assigns the Unicode code point for 'a', which is 97, to the rune variable ch.
To obtain the Unicode code point from a character, you can use an int:
n := int('a')
This assigns the Unicode code point for 'a' to the int variable n.
Here's an example showcasing these conversions:
package main import ( "fmt" ) func main() { ch := rune(97) n := int('a') fmt.Printf("char: %c\n", ch) fmt.Printf("code: %d\n", n) }
When you run this code, it will output:
char: a code: 97
In addition, you can convert an integer numeric value to a string, which interprets the integer value as UTF-8 encoded:
s := string(97)
This assigns the character 'a' to the string variable s.
It's worth noting that 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 valid Unicode code points range are converted to "uFFFD".
The above is the detailed content of How Do I Convert Between Characters and Unicode Code Points in Go?. For more information, please follow other related articles on the PHP Chinese website!