简体   繁体   中英

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 '921,\”' . (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,\”', "Feb 21, 2015"]) AssertionError: u'(921,\”' not found in ['921,\”', 'Feb 21, 2015']

Thanks. \\u201 is a only one char.

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'

Try to decode using 'utf-8':

>>> '921,\u201d'.decode('utf-8')
u'921,\\u201d'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM