12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Some escape sequences allow you to embed absolute binary values into the bytes of astring. For instance, here’s a five-character string that embeds two binary zero bytes:>>> s = 'a\0b\0c'>>> s'a\x00b\x00c'>>> len(s)5In <strong>Python</strong>, the zero (null) byte does not terminate a string the way it typically does inC. Instead, <strong>Python</strong> keeps both the string’s length and text in memory. In fact, nocharacter terminates a string in <strong>Python</strong>. Here’s a string that is all absolute binaryescape codes—a binary 1 and 2 (coded in octal), followed by a binary 3 (coded inhexadecimal):>>> s = '\001\002\x03'>>> s'\x01\x02\x03'>>> len(s)3This becomes more important to know when you process binary data files in <strong>Python</strong>.Because their contents are represented as strings in your scripts, it’s okay to processbinary files that contain any sorts of binary byte values (more on files in Chapter 9). *Finally, as the last entry in Table 7-2 implies, if <strong>Python</strong> does not recognize thecharacter after a \ as being a valid escape code, it simply keeps the backslash in theresulting string:>>> x = "C:\py\code" # Keeps \ literally>>> x'C:\\py\\code'>>> len(x)10Unless you’re able to commit all of Table 7-2 to memory, though, you probablyshouldn’t rely on this behavior. † To code literal backslashes explicitly such that theyare retained in your strings, double them up (\\ is an escape for \) or use raw strings,described in the next section.Raw Strings Suppress EscapesAs we’ve seen, escape sequences are handy for embedding special byte codes withinstrings. Sometimes, though, the special treatment of backslashes for introducing* If you’re especially interested in binary data files, the chief distinction is that you open them in binary mode(using open mode flags with a b, such as 'rb', 'wb', and so on). See also the standard struct module introducedin Chapter 9, which can parse binary data loaded from a file.† In classes, I’ve met people who have indeed committed most or all of this table to memory; I’d normallythink that’s really sick, but for the fact that I’m a member of the set, too.String Literals | 127

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!