title: General string quoting for TCL
body: <p>I'm writing a utility (which happens to be in python) which is generating output in the form of a TCL script. Given some arbitrary string variable (not unicode) in the python, I want to produce a TCL line like</p>
  
  <pre><code>set s something
  </code></pre>
  
  <p>... which will set TCL variable '<code>s</code>' to that exact string, regardless of what strange characters are in it. Without getting too weird, I don't want to make the output messier than needed. I believe a decent approach is</p>
  
  <ol>
  <li><p>if the string is not empty and contains only alphanumerics, and some characters like <code>.-_</code> (but definitely not <code>$"{}\</code>) then it can be used as-is;</p></li>
  <li><p>if it contains only printable characters  and no double-quotes or curly braces (and does not end in backslash ) then simply put <code>{}</code> around it;</p></li>
  <li><p>otherwise, put <code>""</code> around it after using <code>\</code> escapes for <code>"</code> <code>{</code> <code>}</code> <code>\</code> <code>$</code> <code>[</code> <code>]</code>  , and <code>\nnn</code> escapes for non-printing characters.</p></li>
  </ol>
  
  <p>Question: is that the full set of characters which need escaping inside double quotes? I can't find this in the docs. And did I miss something (I almost missed that strings for (2) can't end in \ for instance).</p>
  
  <p>I know there are many other strings which can be quoted by  <code>{}</code>, but it seems difficult to identify them easily. Also, it looks like non-printing characters (in particular, newline) are OK with (2) if you don't mind them being literally present in the TCL output.</p>