How to Escape Strings

You can use escape function from strutils package.

import strutils

let s = "Hello\nWorld"
echo s.escape()

This will print:

Hello\x0AWorld

Current strutils escape function implementation escapes newline into hex value. You can use the following code to do it the way python does.

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()

Output:

Hello\nWorld

Here are documentation links for escape and addEscapeChar functions