如何在Golang中将符文转换为类似`\ u554a`的unicode样式字符串?

时间:2013-05-22 03:02:07

标签: unicode go

如果您运行fmt.Println("\u554a"),则会显示“啊”。

但如何从符文“啊”中获取unicode-style-string \u554a

8 个答案:

答案 0 :(得分:15)

package main

import "fmt"
import "strconv"

func main() {
    quoted := strconv.QuoteRuneToASCII('啊') // quoted = "'\u554a'"
    unquoted := quoted[1:len(quoted)-1]      // unquoted = "\u554a"
    fmt.Println(unquoted)
}

输出:

\u554a

答案 1 :(得分:12)

恕我直言,应该会更好:

func RuneToAscii(r rune) string {
    if r < 128 {
        return string(r)
    } else {
        return "\\u" + strconv.FormatInt(int64(r), 16)
    }
}

答案 2 :(得分:4)

您可以使用fmt.Sprintf%U来获取十六进制值:

test = fmt.Sprintf("%U", '啊')
fmt.Println("\\u" + test[2:]) // Print \u554A

答案 3 :(得分:1)

例如,

package main

import "fmt"

func main() {
    r := rune('啊')
    u := fmt.Sprintf("%U", r)
    fmt.Println(string(r), u)
}

输出:

啊 U+554A

答案 4 :(得分:1)

fmt.Printf("\\u%X", '啊')

http://play.golang.org/p/Jh9ns8Qh15

(大写或小写'x'将控制十六进制字符的大小写)

正如包fmt的documentation所暗示的那样:

  

%U Unicode格式:U + 1234;与“U +%04X”相同

答案 5 :(得分:0)

我想补充一下hardPass的答案。

在Unicode的十六进制表示少于4个字符(例如ü)的情况下,strconv.FormatInt将导致\ufc,这将导致Go中的Unicode语法错误。与Go可以理解的完整\u00fc相对。

使用fmt.Sprintf以十六进制格式对零填充十六进制将解决此问题:

func RuneToAscii(r rune) string {
    if r < 128 {
        return string(r)
    } else {
        return fmt.Sprintf("\\u%04x", r)
    }
}

https://play.golang.org/p/80w29oeBec1

答案 6 :(得分:0)

这可以完成工作。

def plotHighestFive(x1, y1, x2, y2):
    groups = 5
    z = []
    for i in range(len(x1)):
        z.append((x1[i], x2[i]))        # making a list of the states

    # plot settings
    fig, ax = plt.subplots()
    index = np.arange(groups)
    width = 0.35
    opacity = 0.9

    rects1 = plt.bar(index + width, y1, width, alpha = opacity, color = 'c', label = '1999')

    rects2 = plt.bar(index + width, y2, width, alpha = opacity, color = 'r', label = '2017')

    # setting up the plot labels
    plt.xlabel('State')
    plt.ylabel('Number of Deaths per 100,000 Residents')
    plt.title('5 States with the Highest Unintended Overdose Death Rate')
    plt.xticks(index + width/2, z)
    plt.legend()

    plt.tight_layout()
    plt.show()

答案 7 :(得分:0)

package main

import "fmt"

func main() {
    fmt.Printf("%+q", '啊')
}
相关问题