Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Davey,</p> <p>As you say you can just leave the quotes off your string.</p> <p>For a project I'm working on I wanted to be able to represent almost any Python string literal as a value for some of my config options and more to the point I wanted to be able to handle some of them as raw string literals. (I want that config to be able to handle things like \n, \x1b, and so on).</p> <p>In that case I used something like:</p> <pre><code>def EvalStr(s, raw=False): r'''Attempt to evaluate a value as a Python string literal or return s unchanged. Attempts are made to wrap the value in one, then the form of triple quote. If the target contains both forms of triple quote, we'll just punt and return the original argument unmodified. Examples: (But note that this docstring is raw!) &gt;&gt;&gt; EvalStr(r'this\t is a test\n and only a \x5c test') 'this\t is a test\n and only a \\ test' &gt;&gt;&gt; EvalStr(r'this\t is a test\n and only a \x5c test', 'raw') 'this\\t is a test\\n and only a \\x5c test' ''' results = s ## Default returns s unchanged if raw: tmplate1 = 'r"""%s"""' tmplate2 = "r'''%s'''" else: tmplate1 = '"""%s"""' tmplate2 = "'''%s'''" try: results = eval(tmplate1 % s) except SyntaxError: try: results = eval(tmplate2 %s) except SyntaxError: pass return results </code></pre> <p>... which I think will handle anything that doesn't contain both triple-single and triple-double quoted strings.</p> <p>(That one corner case is way beyond my requirements).</p> <p>There is an oddity of this code here on SO; the Syntax highlighter seems to be confused by the fact that my docstring is a <em>raw</em> string. That was necessary to make doctest happy for this particular function).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload