How can I for example convert {"a","b"}
to "{\"a\",\"b\"}"
, so keeping the quotations marks.?
I tried ToString[{"a","b"}]
, but this returns "{a,b}"
in Mathematica 11.2.
Thanks!
4 Answers
ToString[{"a", "b"}, InputForm]
(* "{\"a\", \"b\"}" *)
(thanks @kglr for golfing!)
If you need to get rid of the space between the strings in the string (as per your specification), then use a StringDelete[" "]
operator:
ToString[{"a", "b"}, InputForm] // StringDelete[" "]
(* "{\"a\",\"b\"}" *)
-
1$\begingroup$
StringDelete[" "]
wold also delete any" "
inside the quotation marks, wouldn't it? $\endgroup$– rhermansJul 18, 2019 at 9:57 -
1$\begingroup$ @rhermans yes you're right, may be a bad idea. $\endgroup$– RomanJul 18, 2019 at 9:58
-
2$\begingroup$
ToString[{"a", "b"}, InputForm]
also works. (+1) $\endgroup$– kglrJul 18, 2019 at 10:14
ToString[{"a", "b"} /. x_String :> ("\"" <> x <> "\"")]
seems to work.
StringTemplate["{\"``\",\"``\"}"] @@ {"a", "b"}
"{\"a\",\"b\"}"
There is a short :) function to do this:
StringJoin @ Flatten @ ReplaceAll[RowBox -> List] @
First @ First @ MathLink`CallFrontEnd @ UndocumentedTestFEParserPacket @
ToString @ InputForm @
{"a", "b"}
The idea is to create input form string with quoted characters, then to parse it as an input line (which will remove spaces) then take remaining strings and join them :)