How do I generate a list of strings from a list of assigned variables?
E.g. convert
var1 = 10;
var2 = 11;
var3 = 17;
var4 = 5;
compvar = {var1, var2, var3, var4}; (*all variables assigned*)
into
compvarstr = {"var1", "var2", "var3", "var4"};
Using ToString obviously converts the variables assignments into strings e.g.
compvarstr = ToString[#] & /@ compvar
gives,
{"10", "11", "17", "5"}
I'm after the unassigned variable names as strings e.g.
{"var1", "var2", "var3", "var4"};
Apologies if this is a duplicate - I had a bit of a look and nothing seemed to answer it.
Answer
You must introduce some form of holding in you definition of compvar as otherwise, assuming it is defined after var1, var2, etc., there is no information to retrieve:
var1 = 10;
var2 = 11;
var3 = 17;
var4 = 5;
compvar = {var1, var2, var3, var4};
Definition[compvar]
compvar = {10, 11, 17, 5}
You could use Hold but then you would need to ReleaseHold (or similar) every time you used compvar. Instead I suggest you use SetDelayed and then recover the definition using my step function from:
It returns an expression wrapped in HoldForm:
compvar := {var1, var2, var3, var4};
step[compvar] // InputForm
HoldForm[{var1, var2, var3, var4}]
To convert to a list of strings:
Cases[step[compvar], s_Symbol :> SymbolName @ Unevaluated @ s, {2}]
{"var1", "var2", "var3", "var4"}
Or:
StringSplit[ToString @ step[compvar], ("{" | "," | " " | "}") ..]
{"var1", "var2", "var3", "var4"}
The first method will return Symbols (as strings) only while the second will convert other expressions as well.
Incidentally if you do not need to store your Symbols in a List you could use a more direct form:
compHeld = Hold[var1, var2, var3, var4];
List @@ SymbolName /@ Unevaluated /@ compHeld
{"var1", "var2", "var3", "var4"}
Comments
Post a Comment