Manu Manu - 1 year ago 75
Python Question

How to compare two strings which contain backslashes in Python

I am working with the module ocr from Python and some image return this string

. (The image is a date which looks like 9/21/2015)

Now, if I try to execute this

a == '921,\u201d'

Python automatically escapes the inverted slash (
) in the hardcoded string and the comparison is not equal.

How can I compare two ascii strings without Python interpreting some substrings as unicode characters?

The length is 6
The error is
self.assertIn(res0, [r'921,\u201d', "Feb 21, 2015"])
AssertionError: u'(921,\u201d' not found in ['921,\u201d', 'Feb 21, 2015']

Thanks. \u201 is a only one char.

Answer Source

The easiest way is to use a raw string literal.

a == r'921,\u201d'

This allows you to use literal backslashes without having to escape them (the only restriction is that a string still can't end with an unescaped backslash).

You can also escape the backslash by prepending a backslash to it:

a == '921,\\u201d'