Search code examples
pythonquotesf-string

Is there a Python f-string equivalent of C++’s std::quoted?


In C++, the std::quoted stream manipulator produces a quoted and escaped version of a string:

std::string dirPath = "C:\\Documents\\Oval Office Recordings\\Launch Codes.txt";

std::cout << dirPath << endl; // C:\Documents\Oval Office Recordings\Launch Codes.txt

std::cout << std::quoted(dirPath) << endl; // "C:\\Documents\\Oval Office Recordings\\Launch Codes.txt"

Is there a direct Python f-string equivalent to std::quoted? By “direct,” I mean “built into Python” rather than “you can roll your own version.”

(Context: I have a C++ Quine I use when teaching a theory course that uses std::quoted to keep things simple. I’d like to port it to Python with as little invasive surgery as possible.)


Solution

  • You probably want repr.

    >>> print("C:\\Foo\\Bar")
    C:\Foo\Bar
    >>> print(repr("C:\\Foo\\Bar"))
    'C:\\Foo\\Bar'
    

    Note that single quotes are legal string delimiters in Python. For a quine, you can use %r as a format string for repr; one of the more popular quines is this one-liner:

    _='_=%r;print(_%%_)';print(_%_)

    For an f-string, or format string, you can use the !r modifier:

    >>> s = 'C:\\Foo\\Bar'
    >>> print(f"{s!r}")
    'C:\\Foo\\Bar'
    >>> _='_={!r};print(_.format(_))';print(_.format(_))
    _='_={!r};print(_.format(_))';print(_.format(_))