Strings are immutable sequence objects, with each character representing an element in the sequence. As with all objects, we use methods to perform operations. Strings, being immutable, do not change the instance; each method simply returns a value. This value can be stored as another variable or given as an argument to a function or method.
Methods
Descriptions
s.count(substring, [start,end])
Counts the occurrences of a substring with optional start and end parameters.
s.expandtabs([tabsize])
Replaces tabs with spaces.
s.find(substring, [start, end])
Returns the index of the first occurrence of a substring or returns -1 if the substring is not found.
s.isalnum()
Returns True if all characters are alphanumeric, returns False otherwise.
s.isalpha()
Returns True if all characters are alphabetic, returns False otherwise.
s.isdigit()
Returns True if all characters are digits, returns False otherwise.
s.join(t)
Joins the strings in sequence t .
s.lower()
Converts the string to all lowercase.
s.replace(old, new [maxreplace])
Replaces old substring with new substring.
s.strip([characters])
Removes whitespace or optional characters.
s.split([separator], [maxsplit])
Splits a string separated by whitespace or an optional separator. Returns a list.
List
Method
Description
list(s)
Returns a list of the sequence s.
s.append(x)
Appends element x to the end of s.
s.extend(x)
Appends the list x to s.
s.count(x)
Counts the occurrence of x in s.
s.index(x, [start], [stop])
Returns the smallest index, i , where s[i] == x. Can include optional start and stop index for the search.
s.insert(i,e)
Inserts x at index i.
s.pop(i)
Returns the element i and removes it from the list.
s.remove(x)
Removes x from s.
s.reverse()
Reverses the order of s.
s.sort(key ,[reverse])
Sorts s with optional key and reverse.
Operations and expressions
在Python中以下的值被认为是False:
None类型
False
integer,float, complex 的 zero
空的序列或者map
用户定义的类的实例中诸如__len__()、bool()等方法返回值是0或者False。
此外,其他值均被当作True。
Boolean operations
Operator
Example
not x
Returns True if x is False ; returns False otherwise.
x and y
Returns True if both x and y are True ; returns False otherwise.
x or y
Returns True if either x or y is True ; returns False otherwise.
Build-in data types
Category
Name
Description
None
None
The null object.
Numeric
int
Integer.
float
Floating point number.
complex
Complex number.
bool
Boolean (True, False).
Sequences
str
String of characters.
list
List of arbitrary objects.
Tuple
Group of arbitrary items.
range
Creates a range of integers.
Mapping
dict
Dictionary of key-value pairs.
set
Mutable, unordered collection of unique items.
frozenset
Immutable set.
Sequences
Method
Description
len(s)
Number of elements in s
min(s, [,default=obj, key=func])
The minimum value in s (alphabetically for strings)
max(s, [,default=obj, key=func])
Maximum value in s (alphabetically for strings)
sum(s,[,start=0])
The sum of the elements (returns TypeError if s is not numeric)
all(s)
Returns True if all elements in s are True (that is, not 0 , False , or Null )
any(s)
Checks whether any item in s is True
Operation
Description
s + r
Concatenates two sequences of the same type
s * n
Make n copies of s , where n is an integer
v1, v2 ..., vn = s
Unpacks n variables from s to v1 , v2 , and so on
s[i]
Indexing-returns element i of s
s[i:j:stride]
Slicing returns elements between i and j with optional stride
x in s
Returns True if element x is in s
x not in s
Returns true if element x is not in s
Dictionaries
Method
Description
len(d)
Number of items in d.
d.clear()
Removes all items from d.
d.copy()
Makes a shallow copy of d.
d.fromkeys(s [,value])
Returns a new dictionary with keys from sequence s and values set to value.
d.get(k [,v])
Returns d[k] if found, or else returns v , or None if v is not given.
d.items()
Returns a sequence of key:value pairs in d.
d.keys()
Returns a sequence of keys in d.
d.pop(k [,default])
Returns d[k] and removes it from d . If d[k] is not found, it returns default or raises KeyError.
d.popitem()
Removes a random key:value pair from d and returns it as a tuple.
d.setdefault(k [,v])
Returns d[k] . If d[k] is not found, it returns v and sets d[k] to v.
d.update(b)
Adds all objects from b to d.
d.values()
Returns a sequence of values in d.
Sets
Methods and operations of sets are described in the following table:
Method
Operators
Description
len(s)
Returns the number of elements in s
s.copy()
Returns a shallow copy of s
s.difference(t)
s - t- t2 -...
Returns a set of all items in s but not in t
s.intersection(t)
Returns a set of all items in both t and s
s.isdisjoint(t)
Returns True if s and t have no items in common
s.issubset(t)
s <= t s < t (s != t)
Returns True if all items in s are also in t
s.issuperset(t)
s >= ts > t (s != t)
Returns True if all items in t are also in s
s.symmetric_difference(t)
s ^ t
Returns a set of all items that are in s or t , but not both
s.union(t)
s | t1 | t2|...
Returns a set of all items in s or t
Mutable set objects have additional methods, described in the following table:
Method
Description
s.add(item)
Adds item to s . Has no effect if item is already present.
s.clear()
Removes all items from s.
s.difference_update(t)
Removes all items in s that are also in t.
s.discard(item)
Removes item from s.
s.intersection_update(t)
Removes all items from s that are not in the intersection of s and t.
s.pop()
Returns and removes an arbitrary item from s.
s.remove(item)
Removes item from s.
s.symetric_difference_update(t)
Removes all items from s that are not in the symmetric difference of s and t.
s.update(t)
Adds all the items in an iterable object t to s.
Modules for data structures and algorithms
Collections
The collections module provides more specialized, high, performance alternatives for the built-in data types as well as a utility function to create named tuples. The following table lists the datatypes and operations of the collections module and their descriptions:
Datatype or operation
Description
namedtuple()
Creates tuple subclasses with named fields.
deque
Lists with fast appends and pops either end.
ChainMap
Dictionary like class to create a single view of multiple mappings.
Counter
Dictionary subclass for counting hashable objects.
OrderedDict
Dictionary subclass that remembers the entry order.
defaultdict
Dictionary subclass that calls a function to supply missing values.
UserDict UserList UserString
These three data types are simply wrappers for their underlying base classes. Their use has largely been supplanted by the ability to subclasas their respective base classes directly. Can be used to access the underlying object as an attribute.
Array
The array objects support the following attributes and methods:
Attribute or method
Description
a.typecode
The typecode character used to create the array.
a.itemsize
Size, in bytes, of items stored in the array.
a.append(x)
Appends item x to the end of the array.
a.buffer_info()
Returns the memory location and length of the buffer used to store the array.
a.byteswap()
Swaps the byte order of each item. Used for writing to a machine orfile with a different byte order.
a.count(x)
Returns the number of occurrences of x in a.
a.extend(b)
Appends any iterable, b , to the end of array a.
a.frombytes(s)
Appends items from a string, s , as an array of machine values.
a.fromfile(f, n)
Reads n items, as machine values, from a file object, f , and appends them to a . Raises an EOFError if there are fewer than n items in n.
a.fromlist(l)
Appends items from list l.
a.fromunicode(s)
Extends a with unicode string s . Array a must be of type u or elseValueError is raised.
index(x)
Returns the first (smallest) index of item x.
a.insert(i, x)
Inserts item x before index i.
a.pop([i])
Removes and returns items with index i. Defaults to the last item (i = -1) if not specified.
a.remove(x)
Removes the first occurrence of item x.
a.reverse()
Reverses the order of items.
a.tobytes()
Convert the array to machine values and returns the bytes representation.
a.tofile(f)
Writes all items, as machine values, to file object f.
a.tolist()
Converts the array to a list.
a.tounicode()
Convert an array to unicode string. The array type must be ‘u’ or else a ValueError is raised.
Python Data Types and StructuresStringsStrings are immutable sequence objects, with each character representing an element in the sequence. As with all objects, we use methods to perform operations. Strings, being immutable, do not change the instance; e