# How can one convert an expression to a string while keeping the quotation marks of strings that are part of the expression?

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!

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\"}"    *)

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