Making a String with literal r and variables Python
<p>I'm currently trying to make abstract methods for something like this:</p>

<pre><code>preset_create("TaggingAgain", r'{"weight": 0, "precondition": "{\"_tags\":\"tagged\"}"}')
</code></pre>

<p>In my abstraction the User is able to make Precondition objects within a Preset object which then gets created.</p>

<p>It's currently something like this:</p>

<pre><code>data = str({"weight" : preset.weight, "precondition" : "{}"})
data = data.replace("\'", "\"")
data = data.replace("}\"", "\"%(n)s\":\"%(v)s\"}" % {"n" : precondition.name,"v" : precondition.value})
</code></pre>

<p>(shortened Version because I'll add being able to add multiple preconditions with a "for in" later)</p>

<p>My problem is that the {\"_tags\":\"tagged\"} part needs to be in r'' to work and I don't know how to do that when there are variables in it.</p>

<p>Other code that might help understanding:</p>

<pre><code>class Precondition(object):

    def __init__(self, name, operator, value):
        self.name = name
        self.value = value


class Preset(object):

    def __init__(self, name, weight, *preconditions):
        self.name = name
        self.weight = weight
        self.preconditions = preconditions


precondition = Precondition("_tag", "", "tagged")
createdPreset = Preset("TaggingAgain", "0", precondition)
preset_create(createdPreset)
</code></pre>

<p>If anybody else needs this in the future, heres how I've done it (using json which gre_gor posted a link to in a comment to my question).</p>

<p>Starting with the string:</p>

<pre><code>precon = ("{\"%(n)s\":\"%(v)s\"}" % {"n" : precondition.name,"v" : precondition.value})
</code></pre>

<p>Another way to get this would be to add this to Precondition:</p>

<pre><code>def as_dict(self):
    return {self.name: self.value}
</code></pre>

<p>And then use it like this:</p>

<pre><code>precons = str(precondition.as_dict())
precons = precons.replace("\'", "\"")
</code></pre>

<p>Both of these ways should leave you with a string like this:</p>

<pre><code>{"_tag":"tagged"}
</code></pre>

<p>Then use json.dumps to do the same that r'' would do</p>

<pre><code>precon = json.dumps(precon)
</code></pre>

<p>After that it should look like this:</p>

<pre><code>"{\"_tag\":\"tagged\"}"
</code></pre>

<p>Since json.dumps adds " at the start and at the end, remember to get rid of them if you don't need them.</p>

python string-literals