Davey,
As you say you can just leave the quotes off your string.
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).
In that case I used something like:
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!)
>>> EvalStr(r'this\t is a test\n and only a \x5c test')
'this\t is a test\n and only a \\ test'
>>> 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
... which I think will handle anything that doesn't contain both triple-single and triple-double quoted strings.
(That one corner case is way beyond my requirements).
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 raw string. That was necessary to make doctest happy for this particular function).