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

前端 未结 2 1540
甜味超标
甜味超标 2020-12-11 15:11

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

chr(97) = \'a\'
ord(\'a\') = 97
相关标签:
2条回答
  • 2020-12-11 15:49

    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
    
    0 讨论(0)
  • 2020-12-11 15:54

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

    0 讨论(0)
提交回复
热议问题