9
$\begingroup$

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!

$\endgroup$

4 Answers 4

6
$\begingroup$
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\"}"    *)
$\endgroup$
3
  • 1
    $\begingroup$ StringDelete[" "] wold also delete any " " inside the quotation marks, wouldn't it? $\endgroup$
    – rhermans
    Commented Jul 18, 2019 at 9:57
  • 1
    $\begingroup$ @rhermans yes you're right, may be a bad idea. $\endgroup$
    – Roman
    Commented Jul 18, 2019 at 9:58
  • 2
    $\begingroup$ ToString[{"a", "b"}, InputForm] also works. (+1) $\endgroup$
    – kglr
    Commented Jul 18, 2019 at 10:14
3
$\begingroup$

ToString[{"a", "b"} /. x_String :> ("\"" <> x <> "\"")] seems to work.

$\endgroup$
3
$\begingroup$
StringTemplate["{\"``\",\"``\"}"] @@ {"a", "b"}

"{\"a\",\"b\"}"

$\endgroup$
0
$\begingroup$

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.