nim-lang - 如何在 Nim 中回显带有转义序列的字符串?
问题描述
如果我回显这样的字符串:
let s = "Hello\nworld"
echo s
我得到:
Hello
world
我想输出:
Hello\nworld
我知道如果我正在定义字符串,我可以使用原始字符串文字,但是如果字符串来自例如文件,我该怎么做?
我想我正在寻找类似于 pythonsrepr()
函数的东西。
编辑:Nim 有一个 repr 功能。但是,输出不是我想要的:
let hello = "hello\nworld"
echo repr(hello)
---- Output ----
0x7fc69120b058"hello\10"
"world"
解决方案
您可以使用 strutils 包中的转义函数。
import strutils
let s = "Hello\nWorld"
echo s.escape()
这将打印:
Hello\x0AWorld
当前的 strutils 转义函数实现将换行符转义为十六进制值。您可以使用以下代码按照 python 的方式进行操作。
func escape(s: string): string =
for c in items(s):
case c
of '\0'..'\31', '\34', '\39', '\92', '\127'..'\255':
result.addEscapedChar(c)
else: add(result, c)
let s = "Hello\nWorld"
echo s.escape()
输出:
Hello\nWorld
这是escape和addEscapeChar函数的文档链接
推荐阅读
- c# - ASP.net C# - 站点设置页面 - 使用复选框隐藏不同页面上的 div
- c - 通过指针访问会改变严格的别名语义吗?
- python - PySpark - Combine DF columns into named StructType
- python - Python 2.7 | 使用 RegEx 为变量插入右括号
- java - 通过切换超过 300 个复选框来改善用户体验
- javascript - 替代 `overflow: hidden` 不剪切中间字符
- git - 如何在没有本地 git 存储库的情况下提交到 github 存储库?
- visual-studio - 将 Crystal Formula Workshop 转换为 SQL 和 SSRS
- javascript - 无法扩展类,未定义额外方法
- python - 无法使用 pip 下载适用于 python 3.4、3.6 的 pyinstaller