Yaroslav Bulatov
Yaroslav Bulatov

Reputation: 57893

converting symbols to strings without evaluation

How can I make toStr[list] that takes a list of symbols and returns them as strings? I'd like a=1;toStr[{a}] to give {"a"}

Update 03/02: Leo's recipe works, also to make a version which takes a sequence instead of list I did SetAttribute[toStr2,HoldAll];toStr2[a__]:=toStr[{a}]

Upvotes: 6

Views: 450

Answers (1)

Leo Alekseyev
Leo Alekseyev

Reputation: 13483

You can use HoldForm:

a = 1; b = 2;ToString@HoldForm[{a, b}]

This gives {a, b}. To make it into toStr function, you need to set the attributes so that it doesn't evaluate the arguments:

ClearAll[toStr]; SetAttributes[toStr, {HoldAll, Listable}];
toStr[x_] := ToString@HoldForm[x];
a = 1; b = 2; toStr[{a, b}]

Alternatively, you could use Unevaluated; in the above code toStr[x_] := ToString@Unevaluated[x] would work just as well.

Upvotes: 7

Related Questions