简体   繁体   中英

Python string “b” prefix (byte literals)

I am looking through some unit testing code and I found this:

self.assertIn(b'Hello', res.body)

I know that this means bytes in Python 3 which returns a byte array , as I found here . I believe that the code was written for Python 3.3 and am trying to figure out how it works in other versions (in my case 2.7) The related question that I found had a poorly-written accepted answer with contradictory comments that confused me.

Questions:

  • In what versions of python does b'myString' "work"?
  • How does it behave in python 2.x?
  • How does it behave in python 3.x?
  • Does that have something to do with the byte literal change ?

This is all described in the document you linked.

  • In what versions of python does b'myString' "work"?: 2.6+.
  • How does it behave in python 2.x? It creates a bytes literal—which is the exact same thing as a str literal in 2.x.
  • How does it behave in python 3.x? It creates a bytes literal—which is not the same thing as a str literal in 3.x.
  • Does that have something to do with the byte literal change? Yes. That's the whole point; it lets you write "future compatible" code—or code that works in both 2.6+ and 3.0+ without 2to3 .

Quoting from the first paragraph in the section you linked:

For future compatibility, Python 2.6 adds bytes as a synonym for the str type, and it also supports the b'' notation.

Note that, as it says a few lines down, Python 2.x bytes / str is not exactly the same type as Python 3.x bytes : "most notably, the constructor is completely different". But bytes literals are the same, except in the edge case where you're putting Unicode characters into a bytes literal (which has no defined meaning in 2.x, but does something arbitrary that may sometimes happen to be what you'd hoped, while in 3.x it's a guaranteed SyntaxError ).

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