zcking
Printing raw string stored in variable
I’m trying to figure out how to print out the contents of a string variable, without it interpreting the characters like \n and \t as newlines and tabs. I want to display the “raw” string such as you would do with ~S(raw \n string \t here), however, I cannot pass a variable or interpolate with that sigil.
Is there an idiomatic way to do this with Elixir?
Marked As Solved
kip
Or just call Kernel.inspect/2:
iex> inspect(s)
"\"raw \\n string \\t here\""
iex> inspect(s) |> String.trim("\"")
"raw \\n string \\t here"
Yes, the leading and trailing part might need to be trimmed if you need. But it seems closer to what you’re after - an escaped string.
Also Liked
kip
Kernel.inspect has options to control this via Inspect.Opts:
• :charlists - when :as_charlists all lists will be printed as char
lists, non-printable elements will be escaped.
When :as_lists all lists will be printed as lists.When the default :infer, the list will be printed as a charlist if it is
printable, otherwise as list.
As an example:
iex(6)> inspect [32,33,34], charlists: :as_lists
"[32, 33, 34]"
iex(7)> inspect [32,33,34]
"' !\"'"
You can tell IEx to default to this behaviour by:
hex> IEx.configure [inspect: [charlists: :as_lists]]
:ok
iex> [32,33,34]
[32, 33, 34]








