2
$\begingroup$

How to add quotes to each element in a list? For example, we have a list as:

    list = {{k, \[Beta], Subscript[A, 1], Subscript[b, 1], Subscript[b, 
   2]}, {k, \[Delta], \[CapitalTheta]}}

How to get

{"{k, \[Beta], Subscript[A, 1], Subscript[b, 1], Subscript[b, 
   2]}", "{k, \[Delta], \[CapitalTheta]}"}
$\endgroup$
2
  • $\begingroup$ Is this what you need? "\"" <> ToString[InputForm@#] <> "\"" & /@ list? $\endgroup$
    – N.J.Evans
    Jun 28 at 14:06
  • 2
    $\begingroup$ also ToString[InputForm[#]] & /@ list $\endgroup$
    – Nasser
    Jun 28 at 14:09

2 Answers 2

5
$\begingroup$

Generally you would use ToString for this. That will result in a different formatting for Subscript elements, however. You can wrap the items in InputForm first:

ToString@*InputForm /@ list

or

ToString /@ InputForm /@ list
$\endgroup$
2
$\begingroup$

My attempt is the following:

ToSubscriptHoldForm[expr_?VectorQ] := Block[{asymb, asub},
asymb = Array[Subscript[ToExpression["a"], #] &, 2, 1];
asub = Array[Subscript[ToExpression["a"], #] &, 2, 1, HoldForm[Subscript]];
Which[Length[expr] === 1, expr, Length[expr] === 2, ReplaceAll[Thread[asymb -> expr]][asub], Length[expr] > 2, expr]]

Test:

list2 = ReleaseHold@Map[ToString, Map[Composition[ToSubscriptHoldForm, Level[#, {1}] &], list, {-2}], {-1}]

enter image description here

Go back to your list:

Map[ToExpression, Map[InputForm[#] &, list2], {-1}] === Map[InputForm[#] &, list]
(*True*)

Your list:

Map[ToExpression, Map[InputForm[#] &, list2], {-1}]

enter image description here

$\endgroup$
2
  • 1
    $\begingroup$ Interesting. Based on the expected output provided in the original post, I thought that each of the two lists needed to be string-ified, not the lowest level elements. Maybe the OP can clarify. $\endgroup$
    – lericr
    Jun 28 at 17:46
  • $\begingroup$ You're right @lericr, I misunderstood and went a little further. :) $\endgroup$ Jun 28 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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