0

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')).

Scott Skiles
  • 3,647
  • 6
  • 40
  • 64
  • Does this answer your question? [Convert regular Python string to raw string](https://stackoverflow.com/questions/4415259/convert-regular-python-string-to-raw-string) – wjandrea Jul 25 '20 at 22:11
  • This seems like it might be an [XY problem](https://meta.stackexchange.com/q/66377/343832), so if that doesn't answer your question, please provide a [mre], and we can help you debug. – wjandrea Jul 25 '20 at 22:13
  • Does [this](https://stackoverflow.com/questions/4415259/convert-regular-python-string-to-raw-string) help? – a1426 Jul 25 '20 at 22:37
  • No, thanks. Unfortunately `res.encode('unicode_escape') did not work. – Scott Skiles Jul 25 '20 at 23:49

0 Answers0