5
$\begingroup$

I have the following simple example:

letter= {"a", "b", "c", "d"};
idx=1; (*just for example*)
ToString[Unevaluated[letter[[idx]]]]

the output is letter[[idx]], which is expected.

Question: I wonder and am curious that how one can get the output is letter[[1]] where idx is evaluated while letter[[1]] not (I would like this works for all index in letter)

Well, I thought Unevaluated[letter[[Evaluate[idx]]]], but this for sure will not solve my question. I don't know whether it is possible to solve it. Any comments or suggestions are appreciated, thank you!

$\endgroup$
5
$\begingroup$
ToString[Unevaluated[letter[[#]]]] &@idx
 "letter[[1]]"

Also

With[{idx = idx}, ToString[Unevaluated[letter[[idx]]]]]
"letter[[1]]"

and

ToString[Unevaluated@letter[[idx]]] // StringReplace["idx" -> ToString[idx]]
 "letter[[1]]"
$\endgroup$
5
  • $\begingroup$ cool, thank you! didn't expect so simple, thank you so much! $\endgroup$ – Xuemei Apr 28 '20 at 10:05
  • $\begingroup$ @XuemeiGu, you are most welcome. $\endgroup$ – kglr Apr 28 '20 at 10:17
  • $\begingroup$ @XuemeiGu did you mean to ask for a string output, or that of an expression? If the latter, the second of kglr’s forms is well suited. One might try the following input, everything else considered: With[{idx=idx}, Defer[ letter[[idx]] ] ] which should give you letter[[1]]. $\endgroup$ – CA Trevillian Apr 29 '20 at 6:28
  • $\begingroup$ @CATrevillian, I think for an expression and only part is evaluated. Defer function is nice, I don't know such function. Thank you! $\endgroup$ – Xuemei Apr 29 '20 at 6:40
  • 1
    $\begingroup$ @XuemeiGu No problem! I’m sure kglr can show a better or equivalent way of using such a function, but I use it with some rather questionable combinations of Evaluate and Unevaluated to pull arguments from an expression inputted into a function that uses the results of the expression along with the arguments inputted into the expression, so it can be pretty versatile when you want it to be! $\endgroup$ – CA Trevillian Apr 29 '20 at 6:43

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.