0

If I echo a string like this:

let s = "Hello\nworld"
echo s

I get:

Hello
world

I would like to output: Hello\nworld

I know I can use raw string literals if I'm defining the string, but how do i do it if the string comes from, for example, a file?

I guess I'm looking for something similar to pythons repr() function.

edit: There is a repr function for Nim. However, the output is not what i'm looking for:

let hello = "hello\nworld"
echo repr(hello)

---- Output ----
0x7fc69120b058"hello\10"
"world"
SimplyZ
  • 898
  • 2
  • 9
  • 22
  • Have you tried "Hello\\nworld"? – Bardales Mar 21 '20 at 20:57
  • As i noted in the question, assume I get the string from a file. The content is not known ahead of time. But to answer your question, yes i have tried it, and it works. So does `let s = r"Hello\nworld"`. But that doesn't help me. – SimplyZ Mar 21 '20 at 23:02

2 Answers2

1

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 is documentation links for escape and addEscapeChar functions

0

How about a using:

let s = r"Hello\nWorld"                                                                                                                  
echo s 

will output:

Hello\nWorld
Simon Rowe
  • 1
  • 1
  • 2
  • Please read the question, and the comment I made to the question :) "I know I can use raw string literals if I'm defining the string, but how do i do it if the string comes from, for example, a file?". What you just showed me is called a raw string literal. – SimplyZ Mar 23 '20 at 23:03