Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Suppose that I have an arbitrary variable myVariable. Is there some function fun -- either built-in or one that I can define -- that will return a string "myVariable" when I pass it myVariable?

I would like the output...

myVariable = 123456;
fun[myVariable]

...to give the output...

"myVariable"

... (a string output) for some function fun. Do you have any suggestions? Thanks so much.

share|improve this question

marked as duplicate by Mr.Wizard Jul 24 '14 at 14:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

12  
Looks like you need SymbolName[Unevaluated[myvar]]. – Leonid Shifrin Sep 13 '13 at 2:05
up vote 15 down vote accepted

You can give the function one of the Hold Attributes.

SetAttributes[fun, HoldFirst]

Then as Leonid suggested

fun[var_] := SymbolName[Unevaluated@var] 

Without the hold attribute, this will not work.

share|improve this answer

Any of these could be a start:

ToString@((Trace@myVariable)[[1]])

Or:

StringCases[ToString[Hold[myVariable]],RegularExpression["Hold\\[([[:print:]]+)\\]"] -> "$1"][[1]]
share|improve this answer
    
You don't need to use StringCases/regex if you use HoldForm instead of Hold – R. M. Sep 13 '13 at 2:38

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