|
Operation | Result | Notes |
---|---|---|
x in s |
True if an item of s is equal to x, else False |
(1) |
x not in s |
False if an item of s is
equal to x, else True |
(1) |
s + t |
the concatenation of s and t | (6) |
s * n , n * s |
n shallow copies of s concatenated | (2) |
s[i] |
i'th item of s, origin 0 | (3) |
s[i:j] |
slice of s from i to j | (3), (4) |
s[i:j:k] |
slice of s from i to j with step k | (3), (5) |
len(s) |
length of s | |
min(s) |
smallest item of s | |
max(s) |
largest item of s |
Notes:
in
and not in
operations act like a substring test. In
Python versions before 2.3, x had to be a string of length 1.
In Python 2.3 and beyond, x may be a string of any length.
0
are treated as
0
(which yields an empty sequence of the same type as
s). Note also that the copies are shallow; nested structures
are not copied. This often haunts new Python programmers; consider:
>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
What has happened is that [[]]
is a one-element list containing
an empty list, so all three elements of [[]] * 3
are (pointers to)
this single empty list. Modifying any of the elements of lists
modifies this single list. You can create a list of different lists this
way:
>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
len(s) + i
or
len(s) + j
is substituted. But note that -0
is
still 0
.
i <=
k < j
. If i or j is greater than
len(s)
, use len(s)
. If i is omitted
or None
, use 0
. If j is omitted or None
,
use len(s)
. If i is greater than or equal to j,
the slice is empty.
x = i + n*k
such that
. In other words, the indices
are i
, i+k
, i+2*k
, i+3*k
and so on, stopping when
j is reached (but never including j). If i or j
is greater than len(s)
, use len(s)
. If
i or j are omitted or None
, they become ``end'' values
(which end depends on the sign of k). Note, k cannot
be zero. If k is None
, it is treated like 1
.
s=s+t
or
s+=t
. When applicable, this optimization makes
quadratic run-time much less likely. This optimization is both version
and implementation dependent. For performance sensitive code, it is
preferable to use the str.join() method which assures consistent
linear concatenation performance across versions and implementations.
Changed in version 2.4:
Formerly, string concatenation never occurred in-place.