Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • 3
    literal_eval requires a valid string literal, including begin/end quotes. Adding the quotes (the sample in the question doesn't have them) has several edge cases, depending on what type of input you want to accept. Commented Jul 29, 2011 at 2:29
  • 1
    @Fred very true; but I imagine that in most situations where this is really the problem you want to solve, the begin/end quotes are actually there, even if OP left them out of the example. :) Commented Jul 29, 2011 at 2:57
  • 1
    I'm not sure that really is the problem you'd always want to solve: I'd guess the string_escape codec (as in my answer) exists to fill the real need of transforming escapes without having a string literal. (Pointing out literal_eval is still useful though; I'm the upvote. ;) Commented Jul 29, 2011 at 3:00
  • this fails with prefixed/suffixed space/tab characters since that makes it invalid in python Commented May 5, 2022 at 11:49
  • Well, yes; those weren't part of the specification. "a string that is formatted as if it were a part of Python source code", inherently, begins and ends with a matching pair of either ' or ", not whitespace. If you want to handle that, though, it's trivial to .strip() off first. Commented May 5, 2022 at 12:36