gpt4 book ai didi

string - Go - 是否可以将原始字符串文字转换为解释的字符串文字?

转载 作者:行者123 更新时间:2023-12-01 20:08:15 27 4
gpt4 key购买 nike

是否可以在 Go 中将原始字符串文字转换为解释的字符串文字? (见 language specification)
我有一个原始字符串文字,但我想将解释后的字符串文字输出到控制台,即使用转义序列格式化的文本输出。
例如,打印这个原始字符串文字给出

s := `\033[1mString in bold.\033[0m`
println(s) // \033[1mString in bold.\033[0m
但我想要同样的结果
s := "\033[1mString in bold.\033[0m"
println(s) // String in bold. (In bold)
对于上下文,我正在尝试打印使用转义序列格式化的文本文件的内容
f, _ := := ioutil.ReadFile("file.txt")
println(string(f))
但输出是前一种方式。

最佳答案

使用 strconv.Unquote() :

s := `\033[1mString in bold.\033[0m`

s2, err := strconv.Unquote(`"` + s + `"`)
if err != nil {
panic(err)
}
fmt.Println("normal", s2)
这将输出:

normal String in bold.


请注意 string传递给 strconv.Unquote() 的值必须包含双引号或反引号,并且因为来源 s不包含包装引号,我预先和后缀是这样的:
`"` + s + `"`
查看相关问题:
How do I make raw unicode encoded content readable?
Golang convert integer to unicode character
How to transform Go string literal code to its value?
How to convert escape characters in HTML tags?

关于string - Go - 是否可以将原始字符串文字转换为解释的字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63971092/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com