If I have a string, "foo; \n"
, I can turn this into a raw string with r"foo; \n"
. If I have a variable x = "foo; \n"
, how do I convert x
into a raw string? I tried y = rf"{x}"
but this did not work.
Motivation:
I have a python string variable, res
. I compute res as
big_string = """foo; ${bar}"""
from string import Template
t = Template(big_string)
res = t.substitute(bar="baz")
As such, res
is a variable. I'd like to convert this variable into a raw string. The reason is I am going to POST it as JSON, but I am getting json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 620 (char 619)
. Previously, when testing I fixed this by converting my string to a raw string with: x = r"""foo; baz"""
(keeping in line with the example above). Now I am not dealing with a big raw string. I am dealing with a variable that is a JSON representation of a string where I have replaced a single variable, bar
above, with a list for a query, and now I want to convert this string into a raw string (e.g. r"foo; baz"
, yes I realize this is not valid JSON).
Update: As per this question I need a raw string. The question and answer flagged in the comments as duplicate do not work (res.encode('unicode_escape')
).