Python-quote a string in Python with proper escapes

Viewed 18

I want to take a string, and return the Python-style quoted representation of this string. How can I do this correctly, ie. respecting Python syntax?

Some examples of what I want:

  • cat -> "cat"
  • "dog" -> '"dog"'
  • 'elephant' -> "'elephant'"
  • "what's up" -> '"what\'s up "'
  • '''"""seriously dude?"""''' -> '\'\'\'"""seriously dude?"""\'\'\'

Note that quotes are correctly escaped, which is more complex than simply doing f'"{s}"' like recommended in some similar questions.

I know that there can be multiple ways to represent the same string in Python ("cat", 'cat', """cat""", "c"'a'"t", ...). I don't have a preference as to which one is used, just so long as the result would parse in Python as a valid string literal.

For context: My Python program generates Python code. Part of user input is some raw strings, which must be transformed into quoted Python literals in the output.

1 Answers

I could not find a Python specific way to do this, but coincidentally JSON has similar string literal syntax:

def quote_string(s: str) -> str:
    # JSON string literals are a subset of Python (?)
    return json.dumps(s)
  • I'm not sure if this is always correct - I think some escape sequences may be valid in Python and not in JSON or vice versa
  • JSON doesn't have the many quote flavors, so it can't efficiently utilize some optimizations like 'no "big" deal' instead of "no \"big\" deal"

There's probably a better way than this, but I can't think of one.

Related