Equivalent of python's ord(), chr() in go?

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

Equivalent of python's ord(), chr() in go?

问题

在Go语言中,与Python的chr()和ord()函数等效的函数是string()和int()函数。

在Go语言中,使用string()函数将整数转换为对应的Unicode字符。例如,string(97)将返回字符'a'。

而使用int()函数将字符转换为对应的Unicode码点。例如,int('a')将返回97。

请注意,Go语言中的字符类型是rune,它表示一个Unicode码点。因此,可以使用rune类型来存储和操作字符。

英文:

What is the equivalent of python's chr() and ord() functions in golang?

chr(97) = 'a'
ord('a') = 97

答案1

得分: 26

它们被支持为简单的转换:

ch := rune(97)
n := int('a')
fmt.Printf("char: %c\n", ch)
fmt.Printf("code: %d\n", n)

输出结果(在Go Playground上尝试):

char: a
code: 97

注意:你也可以将整数数值转换为string类型,它基本上将整数值解释为UTF-8编码的值:

s := string(97)
fmt.Printf("text: %s\n", s) // 输出结果:text: a

将有符号或无符号整数值转换为字符串类型会生成一个包含整数的UTF-8表示的字符串。超出有效Unicode代码点范围的值会被转换为"\uFFFD"。

英文:

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

答案2

得分: 2

似乎简单的uint8('a')将产生正确的输出。要将整数转换为字符串,使用string(98)即可:

uint8('g') // 103
string(112) // p
英文:

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

huangapple
  • 本文由 发表于 2015年4月28日 16:50:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/29914662.html
匿名

发表评论

匿名网友

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

确定