Function Repository Resource:

ConvertStringsToSymbols

Source Notebook

Convert strings inside an expression to symbols without evaluating them further

Contributed by: Sjoerd Smit

ResourceFunction["ConvertStringsToSymbols"][expr, str]

replaces all instances of str in expr with the symbol of that name.

ResourceFunction["ConvertStringsToSymbols"][expr, str"context`"]

creates the symbol in a given context.

ResourceFunction["ConvertStringsToSymbols"][expr, {spec1,spec2,}]

replaces multiple strings with symbols.

Details

ResourceFunction["ConvertStringsToSymbols"] has the attribute HoldFirst.
Use Evaluate if you want to evaluate expr to create strings programmatically or use With to insert programmatically generated strings into expr.
The context specification Automatic is equivalent to not specifying a context.

Examples

Basic Examples (4) 

Convert "x" to x in a polynomial:

In[1]:=
Clear[x]
ResourceFunction["ConvertStringsToSymbols"][2 "x" + 1, "x"]
Out[2]=
In[3]:=
% /. x -> 5
Out[3]=

If the input expression is in held form, x will not evaluate to any value it might have:

In[4]:=
x = 1;
ResourceFunction["ConvertStringsToSymbols"][Hold[2 "x" + 1], "x"] // FullForm
Out[5]=

The replacement is done before the expression is evaluated, so functions like Set (=) and SetDelayed (:=) work as expected:

In[6]:=
x = 1;
ResourceFunction["ConvertStringsToSymbols"]["x" = 2, "x"]
Out[7]=

The value of x changed:

In[8]:=
x
Out[8]=

Scope (3) 

Convert multiple strings to symbols:

In[9]:=
ResourceFunction[
 "ConvertStringsToSymbols"][{"x", "y"} = {1, 2}, {"x", "y"}]
Out[9]=
In[10]:=
{x, y}
Out[10]=

Put x in a different context:

In[11]:=
ResourceFunction["ConvertStringsToSymbols"]["x" = 3, "x" -> "foo`"]
Out[11]=
In[12]:=
{x, foo`x}
Out[12]=

Create symbols in different contexts. The context specification Automatic is equivalent to not specifying a context:

In[13]:=
ResourceFunction["ConvertStringsToSymbols"][
  Hold["a", "b", "c", "d", "e"],
  {{"a", "b"} -> "foo`", "c" -> "bar`", "d" -> Automatic, "e"}
  ] // FullForm
Out[13]=

Applications (3) 

Construct a range of symbols programmatically and populate them with values:

In[14]:=
With[{
  syms = "x" <> ToString[#] & /@ Range[10]
  },
 ResourceFunction["ConvertStringsToSymbols"][
  syms = Range[Length[syms]]^2, syms]
 ]
Out[14]=

Check the values:

In[15]:=
{x1, x2, x3, x4, x5, x6, x7, x8, x9, x10}
Out[15]=

This works even when the symbols already have values:

In[16]:=
With[{
   syms = "x" <> ToString[#] & /@ Range[10]
   },
  ResourceFunction["ConvertStringsToSymbols"][
   syms = Range[Length[syms]]^3, syms]
  ];
{x1, x2, x3, x4, x5, x6, x7, x8, x9, x10}
Out[17]=

Publisher

Sjoerd Smit

Version History

  • 1.0.0 – 09 May 2022

License Information