Python - Backslash Quoting in String Literals

I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:

>>> foo = 'baz "\"'
>>> foo
'baz ""'

So instead of baz "\" like I want I'm getting baz "". If I then try to escape the backslash, it doesn't help either:

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'

Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?

Answers


You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print foo
baz "\"

Incidentally, there's another string form which might be a bit clearer:

>>> print r'baz "\"'
baz "\"

Need Your Help

How mature is Ebean or Siena?

java orm persistence siena ebean

In the last time I heard a lot of complaining about hibernate. And indeed I have some painful experiences with hibernate too. So I read about Ebean and Siena.

How to Properly Structure my Android App, Classes, Views, Databases, Made Simple?

android sql class design data-structures

I'm having a hell of time grasping the best way to "package" my Android app into logical components, my objective is to make an app that is easy to update and add new features to.

What's in your PHP toolset?

php devtools

Every PHP programmer likely uses at least some form of a template engine and a database abstraction layer, but apart from those what extras do you consider essential or would recommend your fellow

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.