Text stringlengths 1 9.41k |
|---|
Raw strings are useful if you code paths using
```
native Windows backslashes, though.
Despite its role, even a raw string cannot end in a single backslash, because the backslash escapes the following quote character—you still
must escape the surrounding quote character to embed it in the string.
That is, r"...\" is ... |
If you need to end a raw string with a
single backslash, you can use two and slice off the second
(r'1\nb\tc\\'[:-1]), tack one on manually (r'1\nb\tc' + '\\'), or skip
the raw string syntax and just double up the backslashes in a normal
string ('1\\nb\\tc\\'). |
All three of these forms create the same eightcharacter string containing three backslashes.
###### Triple Quotes Code Multiline Block Strings
So far, you’ve seen single quotes, double quotes, escapes, and raw strings in action.
Python also has a triple-quoted string literal format, sometimes called a block string,
t... |
This form begins with
three quotes (of either the single or double variety), is followed by any number of lines
of text, and is closed with the same triple-quote sequence that opened it. |
Single and
double quotes embedded in the string’s text may be, but do not have to be, escaped—
the string does not end until Python sees three unescaped quotes of the same kind used
to start the literal. |
For example:
```
>>> mantra = """Always look
... on the bright
... |
side of life."""
>>>
>>> mantra
'Always look\n on the bright\nside of life.'
```
**|**
-----
This string spans three lines (in some interfaces, the interactive prompt changes
to ... |
on continuation lines; IDLE simply drops down one line). |
Python collects all the
triple-quoted text into a single multiline string, with embedded newline characters
(\n) at the places where your code has line breaks. |
Notice that, as in the literal, the
second line in the result has a leading space, but the third does not—what you type is
truly what you get. |
To see the string with the newlines interpreted, print it instead of
echoing:
```
>>> print(mantra)
Always look
on the bright
side of life.
```
Triple-quoted strings are useful any time you need multiline text in your program; for
example, to embed multiline error messages or HTML or XML code in your source
c... |
You can embed such blocks directly in your scripts without resorting to
external text files or explicit concatenation and newline characters.
Triple-quoted strings are also commonly used for documentation strings, which are
string literals that are taken as comments when they appear at specific points in your
file (mo... |
These don’t have to be triple-quoted blocks, but
they usually are to allow for multiline comments.
Finally, triple-quoted strings are also sometimes used as a “horribly hackish” way to
temporarily disable lines of code during development (OK, it’s not really too horrible,
and it’s actually a fairly common practice). |
If you wish to turn off a few lines of code
and run your script again, simply put three quotes above and below them, like this:
```
X = 1
"""
import os # Disable this code temporarily
print(os.getcwd())
"""
Y = 2
```
I said this was hackish because Python really does make a string out of the l... |
For large
sections of code, it’s also easier than manually adding hash marks before each line and
later removing them. |
This is especially true if you are using a text editor that does not
have support for editing Python code specifically. |
In Python, practicality often beats
aesthetics.
###### Strings in Action
Once you’ve created a string with the literal expressions we just met, you will almost
certainly want to do things with it. |
This section and the next two demonstrate string
expressions, methods, and formatting—the first line of text-processing tools in the
Python language.
**|**
-----
###### Basic Operations
Let’s begin by interacting with the Python interpreter to illustrate the basic string operations listed earlier in Table 7-1. |
Strings can be concatenated using the + operator
and repeated using the * operator:
```
% python
```
`>>> len('abc')` _# Length: number of items_
```
3
```
`>>> 'abc' + 'def'` _# Concatenation: a new string_
```
'abcdef'
```
`>>> 'Ni!' * 4` _# Repetition: like "Ni!" + "Ni!" + ..._
```
'Ni!Ni!Ni!Ni!'
```
For... |
Repetition is like adding a string to itself a number of times. |
In both
cases, Python lets you create arbitrarily sized strings; there’s no need to predeclare
anything in Python, including the sizes of data structures.[‡] The len built-in function
returns the length of a string (or any other object with a length).
Repetition may seem a bit obscure at first, but it comes in handy i... |
For example, to print a line of 80 dashes, you can count up to 80, or let
Python count for you:
`>>> print('-------` `...more...` `---')` _# 80 dashes, the hard way_
`>>> print('-' * 80)` _# 80 dashes, the easy way_
Notice that operator overloading is at work here already: we’re using the same + and
```
* operators t... |
Python does
```
the correct operation because it knows the types of the objects being added and multiplied. But be careful: the rules aren’t quite as liberal as you might expect. |
For instance,
Python doesn’t allow you to mix numbers and strings in + expressions: 'abc'+9 raises
an error instead of automatically converting 9 to a string.
As shown in the last row in Table 7-1, you can also iterate over strings in loops using
```
for statements and test membership for both characters and substring... |
For substrings, in is much like the
```
str.find() method covered later in this chapter, but it returns a Boolean result instead
```
of the substring’s position:
```
>>> myjob = "hacker"
```
`>>> for c in myjob: print(c, end=' ')` _# Step through items_
```
...
```
‡ Unlike with C character arrays, you don’t nee... |
Each object keeps track of the number of names, data structures, etc., that
reference it; when the count reaches zero, Python frees the object’s space. |
This scheme means Python doesn’t
have to stop and scan all the memory to find unused space to free (an additional garbage component also
collects cyclic objects).
**|**
-----
```
h a c k e r
```
`>>> "k" in myjob` _# Found_
```
True
```
`>>> "z" in myjob` _# Not found_
```
False
```
`>>> 'spam' in 'abcspam... |
In effect, the variable c becomes a cursor
stepping across the string here. |
We will discuss iteration tools like these and others
listed in Table 7-1 in more detail later in this book (especially in Chapters 14 and 20).
###### Indexing and Slicing
Because strings are defined as ordered collections of characters, we can access their
components by position. |
In Python, characters in a string are fetched by indexing—
providing the numeric offset of the desired component in square brackets after the
string. |
You get back the one-character string at the specified position.
As in the C language, Python offsets start at 0 and end at one less than the length of
the string. |
Unlike C, however, Python also lets you fetch items from sequences such
as strings using negative offsets. Technically, a negative offset is added to the length of
a string to derive a positive offset. |
You can also think of negative offsets as counting
backward from the end. |
The following interaction demonstrates:
```
>>> S = 'spam'
```
`>>> S[0], S[−2]` _# Indexing from front or end_
```
('s', 'a')
```
`>>> S[1:3], S[1:], S[:−1]` _# Slicing: extract a section_
```
('pa', 'pam', 'spa')
```
The first line defines a four-character string and assigns it the name S. |
The next line
indexes it in two ways: S[0] fetches the item at offset 0 from the left (the one-character
string 's'), and S[−2] gets the item at offset 2 back from the end (or equivalently, at
offset (4 + (–2)) from the front). |
Offsets and slices map to cells as shown in Figure 7-1.[§]
The last line in the preceding example demonstrates slicing, a generalized form of indexing that returns an entire section, not a single item. |
Probably the best way to think
of slicing is that it is a type of parsing (analyzing structure), especially when applied to
strings—it allows us to extract an entire section (substring) in a single step. |
Slices can
be used to extract columns of data, chop off leading and trailing text, and more. |
In fact,
we’ll explore slicing in the context of text parsing later in this chapter.
The basics of slicing are straightforward. |
When you index a sequence object such as a
string on a pair of offsets separated by a colon, Python returns a new object containing
§ More mathematically minded readers (and students in my classes) sometimes detect a small asymmetry here:
the leftmost item is at offset 0, but the rightmost is at offset –1. |
Alas, there is no such thing as a distinct –0
value in Python.
**|**
-----
_Figure 7-1. |
Offsets and slices: positive offsets start from the left end (offset 0 is the first item), and_
_negatives count back from the right end (offset −1 is the last item). |
Either kind of offset can be used_
_to give positions in indexing and slicing operations._
the contiguous section identified by the offset pair. |
The left offset is taken to be the
lower bound (inclusive), and the right is the upper bound (noninclusive). |
That is, Python
fetches all items from the lower bound up to but not including the upper bound, and
returns a new object containing the fetched items. |
If omitted, the left and right bounds
default to 0 and the length of the object you are slicing, respectively.
For instance, in the example we just saw, S[1:3] extracts the items at offsets 1 and 2:
it grabs the second and third items, and stops before the fourth item at offset 3. |
Next,
```
S[1:] gets all items beyond the first—the upper bound, which is not specified, defaults
```
to the length of the string. |
Finally, S[:−1] fetches all but the last item—the lower bound
defaults to 0, and −1 refers to the last item, noninclusive.
This may seem confusing at first glance, but indexing and slicing are simple and powerful tools to use, once you get the knack. |
Remember, if you’re unsure about the effects
of a slice, try it out interactively. |
In the next chapter, you’ll see that it’s even possible
to change an entire section of another object in one step by assigning to a slice (though
not for immutables like strings). |
Here’s a summary of the details for reference:
- Indexing (S[i]) fetches components at offsets:
—The first item is at offset 0.
—Negative indexes mean to count backward from the end or right.
— S[0] fetches the first item.
— S[−2] fetches the second item from the end (like S[len(S)−2]).
- Slicing (S[i:j]) extracts ... |
This isn’t very useful for immutable
objects like strings, but it comes in handy for objects that may be changed in-place,
such as lists.
In the next chapter, you’ll see that the syntax used to index by offset (square brackets)
is used to index dictionaries by key as well; the operations look the same but have
differe... |
The step is added to the index of each item extracted. |
The full-blown form of a slice is now X[I:J:K], which means “extract all the
items in X, from offset I through J−1, by K.” The third limit, K, defaults to 1, which is
why normally all items in a slice are extracted from left to right. |
If you specify an explicit
value, however, you can use the third limit to skip items or to reverse their order.
For instance, X[1:10:2] will fetch every other item in X from offsets 1–9; that is, it will
collect the items at offsets 1, 3, 5, 7, and 9. |
As usual, the first and second limits default
to 0 and the length of the sequence, respectively, so X[::2] gets every other item from
the beginning to the end of the sequence:
```
>>> S = 'abcdefghijklmnop'
>>> S[1:10:2]
'bdfhj'
>>> S[::2]
'acegikmo'
```
You can also use a negative stride. |
For example, the slicing expression "hello"[::−1]
returns the new string "olleh"—the first two bounds default to 0 and the length of the
sequence, as before, and a stride of −1 indicates that the slice should go from right to
left instead of the usual left to right. |
The effect, therefore, is to reverse the sequence:
```
>>> S = 'hello'
>>> S[::−1]
'olleh'
```
With a negative stride, the meanings of the first two bounds are essentially reversed.
That is, the slice S[5:1:−1] fetches the items from 2 to 5, in reverse order (the result
contains items from offsets 5, 4, 3, and 2... |
We’ll revisit three-limit slices again later in this book, in conjunction
with the for loop statement.
Later in the book, we’ll also learn that slicing is equivalent to indexing with a _slice_
_object, a finding of importance to class writers seeking to support both operations:_
`>>> 'spam'[1:3]` _# Slicing syntax_
`... |
Because you won’t be able to make much sense of real use cases
until you’ve seen more of the Python picture, these sidebars necessarily contain many
references to topics not introduced yet; at most, you should consider them previews of
ways that you may find these abstract language concepts useful for common programmin... |
This leads to a very typical application of slices: a single slice expression can be
used to return all but the first item of a list. |
Here, sys.argv[1:] returns the desired list,
```
['−a', '−b', '−c']. |
You can then process this list without having to accommodate the
```
program name at the front.
Slices are also often used to clean up lines read from input files. |
If you know that a line
will have an end-of-line character at the end (a \n newline marker), you can get rid of
it with a single expression such as line[:−1], which extracts all but the last character
in the line (the lower limit defaults to 0). |
In both cases, slices do the job of logic that
must be explicit in a lower-level language.
**|**
-----
###### String Conversion Tools
One of Python’s design mottos is that it refuses the temptation to guess. |
As a prime
example, you cannot add a number and a string together in Python, even if the string
looks like a number (i.e., is all digits):
```
>>> "42" + 1
TypeError: cannot concatenate 'str' and 'int' objects
```
This is by design: because + can mean both addition and concatenation, the choice of
conversion would... |
So, Python treats this as an error. |
In Python, magic
is generally omitted if it will make your life more complex.
What to do, then, if your script obtains a number as a text string from a file or user
interface? |
The trick is that you need to employ conversion tools before you can treat a
string like a number, or vice versa. |
For instance:
`>>> int("42"), str(42)` _# Convert from/to string_
```
(42, '42')
```
`>>> repr(42)` _# Convert to as-code string_
```
'42'
```
The int function converts a string to a number, and the str function converts a number
to its string representation (essentially, what it looks like when printed). |
The `repr`
function (and the older backquotes expression, removed in Python 3.0) also converts
an object to its string representation, but returns the object as a string of code that can
be rerun to recreate the object. |
For strings, the result has quotes around it if displayed
with a print statement:
```
>>> print(str('spam'), repr('spam'))
('spam', "'spam'")
```
See the sidebar “str and repr Display Formats” on page 116 for more on this topic. |
Of
these, int and str are the generally prescribed conversion techniques.
Now, although you can’t mix strings and number types around operators such as +,
you can manually convert operands before that operation if needed:
```
>>> S = "42"
>>> I = 1
>>> S + I
TypeError: cannot concatenate 'str' and 'int' object... |
The functions int
and float convert only to numbers, but this restriction means they are usually faster
(and more secure, because they do not accept arbitrary expression code). |
As we saw
briefly in Chapter 5, the string formatting expression also provides a way to convert
numbers to strings. |
We’ll discuss formatting further later in this chapter.
###### Character code conversions
On the subject of conversions, it is also possible to convert a single character to its
underlying ASCII integer code by passing it to the built-in ord function—this returns
the actual binary value of the corresponding byte in m... |
The chr function performs
the inverse operation, taking an ASCII integer code and converting it to the corresponding character:
```
>>> ord('s')
115
>>> chr(115)
's'
```
You can use a loop to apply these functions to all characters in a string. |
These tools can
also be used to perform a sort of string-based math. |
To advance to the next character,
for example, convert and do the math in integer:
```
>>> S = '5'
>>> S = chr(ord(S) + 1)
>>> S
'6'
>>> S = chr(ord(S) + 1)
>>> S
'7'
```
At least for single-character strings, this provides an alternative to using the built-in
```
int function to convert from string to i... |
Each time through the loop, multiply
the current value by 2 and add the next digit’s integer value:
`>>> B = '1101'` _# Convert binary digits to integer with ord_
```
>>> I = 0
>>> while B != '':
... |
I = I * 2 + (ord(B[0]) - ord('0'))
... |
B = B[1:]
...
>>> I
13
```
A left-shift operation (I << 1) would have the same effect as multiplying by 2 here.
We’ll leave this change as a suggested exercise, though, both because we haven’t studied loops in detail yet and because the int and bin built-ins we met in Chapter 5 handle
binary conversion tasks for... |
The immutable part means that you can’t
change a string in-place (e.g., by assigning to an index):
```
>>> S = 'spam'
>>> S[0] = "x"
Raises an error!
```
So, how do you modify text information in Python? |
To change a string, you need to
build and assign a new string using tools such as concatenation and slicing, and then,
if desired, assign the result back to the string’s original name:
`>>> S = S + 'SPAM!'` _# To change a string, make a new one_
```
>>> S
'spamSPAM!'
>>> S = S[:4] + 'Burger' + S[−1]
>>> S
's... |
The second example replaces four characters with six by slicing, indexing, and
concatenating. |
As you’ll see in the next section, you can achieve similar effects with
string method calls like replace:
**|**
-----
```
>>> S = 'splot'
>>> S = S.replace('pl', 'pamal')
>>> S
'spamalot'
```
Like every operation that yields a new string value, string methods generate new string
objects. |
If you want to retain those objects, you can assign them to variable names.
Generating a new string object for each string change is not as inefficient as it may
sound—remember, as discussed in the preceding chapter, Python automatically garbage collects (reclaims the space of) old unused string objects as you go, so n... |
Python is usually more efficient than you
might expect.
Finally, it’s also possible to build up new text values with string formatting expressions.
Both of the following substitute objects into a string, in a sense converting the objects
to strings and changing the original string according to a format specification:
... |
We’ll study formatting later in this chapter; as we’ll find,
formatting turns out to be more general and useful than this example implies. |
Because
the second of the preceding calls is provided as a method, though, let’s get a handle on
string method calls before we explore formatting further.
As we’ll see in Chapter 36, Python 3.0 and 2.6 introduce a new string
type known as bytearray, which is mutable and so may be changed in
place. |
bytearray objects aren’t really strings; they’re sequences of small,
8-bit integers. However, they support most of the same operations as
normal strings and print as ASCII characters when displayed. |
As such,
they provide another option for large amounts of text that must be
changed frequently. |
In Chapter 36 we’ll also see that ord and chr handle
Unicode characters, too, which might not be stored in single bytes.
###### String Methods
In addition to expression operators, strings provide a set of methods that implement
more sophisticated text-processing tasks. |
Methods are simply functions that are associated with particular objects. Technically, they are attributes attached to objects that
happen to reference callable functions. |
In Python, expressions and built-in functions
may work across a range of types, but methods are generally specific to object types—
string methods, for example, work only on string objects. |
The method sets of some
types intersect in Python 3.0 (e.g., many types have a count method), but they are still
more type-specific than other tools.
**|**
-----
In finer-grained detail, functions are packages of code, and method calls combine two
operations at once (an attribute fetch and a call):
_Attribute fetc... |
The method call
expression object.method(arguments) is evaluated from left to right—Python will first
fetch the method of the object and then call it, passing in the arguments. |
If the method
computes a result, it will come back as the result of the entire method-call expression.
As you’ll see throughout this part of the book, most objects have callable methods, and
all are accessed using this same method-call syntax. |
To call an object method, as you’ll
see in the following sections, you have to go through an existing object.
Table 7-3 summarizes the methods and call patterns for built-in string objects in Python
3.0; these change frequently, so be sure to check Python’s standard library manual for
the most up-to-date list, or run ... |
Python 2.6’s string
methods vary slightly; it includes a decode, for example, because of its different handling
of Unicode data (something we’ll discuss in Chapter 36). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.