- The last character in a raw string can’t be a backslash, If the last character(before the final quote) is a backslash, Python won’t know whether to end the string or not.raw字串最後一個字元不能是\
- 如果確實需要最後一個字元是\,需要將\放到另外一個字串裡
>>> print r"c:\Prpgram Files\foo\bar" "\\"
c:\Prpgram Files\foo\bar\
- Modules are extensions that can be Imported into Python to extend its capabilities.
- You can change a list, but you can’t change a tuple. Tuple can be used as dictionary keys, but lists can’t. Because you aren’t allowed to modify keys.
- A string is just a sequence of characters. The index 0 refers to the first element.
- Slicing: the first index is the number of the first element you want to include, however, the last index is the number of the first element after you slice. In short, the first is inclusive, and the second is exclusive.
- if the slice continues to the end of sequence, you may simply leave out the last index. Numbers[-3:], if you want to copy the entire sequence, you may leave out both indices. Numbers[:]
- The step length is one – the slice ‘moves’ from one element to the next, returning all the elements between the start and end
- The step size can be negative, which means extracting the elements from right to left: when using a negative step size, you have to have a first limit(start index) that is higher than the second one.
- Lists are mutable—that is, you can change their contents.
- list works with all kinds of sequence, not just string:list(‘hello’), if you want to convert a list of characters back to string, use ‘’.join(somelist)
- the pop method removes an element(by default the last one) from the list and returns it
- If you want to iterate over a sequence in reverse, you can use the reversed function. This function doesn’t return a list. Though, it returns an iterator.
- The sort method is used to sort lists in place. Sorting “in place” means changing the original so its elements are in sorted order, rather than simply returning a sorted copy of the list. Notes that sort modifies list but return nothing!
- sorted function can be used on any sequence, but will always return a list
- Tuple can’t be changed!
- Strings are immutable, so all kinds of item or slice assignments are illegal
- if no separator is supplied, the default is to split on all runs of consecutive whitespace characters(spaces, tabs, newlines, and so on)
- Keys are unique within a dictionary (and any other kind of mapping), while values may not be.
- You can assign a value to a key even if that key isn’t in the dictionary to begin with. A new item will be created.
- when you replace a value in the copy, the original is unaffected. However, if you modify a value (in place, without replacing it), the original is changed as well because the same value is stored there.
- When you use get to access a nonexistent key, there is no exception. Instead, you get the value None. If the key is there, get works like ordinary dictionary lookup.
- Popitem pops off a random item because dictionaries don’t have a “last element” or any other whatsoever.
- Setdefault sets the value corresponding to the given key If it is not already in the dictionary. When the key is missing, setdefault returns the default and updates the dictionary accordingly. If the key is present, its value is returned and the dictionary is left unchanged. The default is optional, as with get; if it is left out, None is used.
- The update method updates one dictionary with the items of another: The items in the supplied dictionary are added to the old one, overwriting any items there with the same keys.
- In general, you should not use += with strings, especially if you are building a large string piece by piece in a loop. Each addition and assignment needs to create a new string, and that takes time, making your program slower. A much better approach is to append the small strings to a list, and use the string method join to create the big string when your list is finished.
- The standard values False and None, numeric zero of all types (including float, long, and so on), empty sequences (such as empty strings, tuples, and lists), and empty dictionaries are all false. Everything else is interrupted as true, including the special value True.
- Is tests for identity, rather than equality. X=y=[1, 2, 3], z = [1, 2, 3], x==z(True), x ix z (False). The variables x and y have been bound to the same list, while z is simply bound to another list that happens to contain the same values in the same order. They may be equal, but they aren’t the same object.
- Use == to see if two objects are equal, and use is to see if they are identical (the same object). Caution: Avoid the use of is with basic, immutable values such as numbers and strings. The result is unpredictable because of the way Python handles these objects internally.
- Short-Circuit logic: the Boolean operators are often called logic operator, the second value is sometimes “short-circuited”
- A string with one space is not empty, and therefore not false.
- Zips parallel iterate together the sequences, returning a list of tuples. The zip function works with as many as you want, it stops when the shortest sequence is “used up”
- Enumerate iterate over index-value pairs, where the indices are supplied automatically
- Reverse a string: ‘’.join(reversed(‘someStr’))
- >>> girls = ['alice', 'bernice', 'clarice']
>>> boys = ['chris', 'arnold', 'bob']
>>> [b '+' g for b in boys for g in girls if b[0] == g[0] ]
>>> letterGirls ={}
>>> for girl in girls:
letterGirls.setdefault(girl[0], []).append(girl)
>>> print [b + '+' + g for b in boys for g in letterGirls[b[0]]]
- Del just delete the name, not the list itself.
- page = download_page() freqs = compute_frequencies(page) for word, freq in freqs: print word, freq
- >>> def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
- return result
- The variables you write after your function name in def statements are often called formal parameters of the function, while the values you supply when you call the function are called the actual parameters or arguments.
- Assigning a new value to a parameter inside a function won’t change the outside world at all.
- Strings (and numbers and tuples) are immutable. You can’t modify them
- When two variables refer to the same list, they refer to the same list, if you want to avoid this, you have to make a copy of the list. When you do slicing on a sequence, the returned slice is always a copy. If you make a slice of the entire list you get a copy.
- Names that are local to a function, including parameters, do not clash with names outside of the function (that is, global ones)
- if you really want to modify your parameter, you can wrap your value in a list.
- Each time a function is called, a new namespace is created for that specific call
- the map function maps one sequence into another (of the same length) by applying a function to each of the elements.
- Object means a collection of data (attributes) with a set of methods for accessing and manipulating those data.
- self refers to the object itself
- Methods have their first parameter bound to the instance they belong to: you don’t have supply it.
- If a method is implemented differently by two or more of the superclasses, you must be careful about the order of these superclasses (in the class statement): The methods in the earlier classes override the methods in the latter ones.
- If an exception is raised inside a function, and isn’t handled there, it propagates to the place where the function was called, If it isn’t handled there either, it continues to propagating until it reaches the main program (the global scope), and if there is no exception handler there, the program halts with an error message and some information about what went wrong (a stack trace).
- Static methods and class methods are created by wrapping methods in objects of the staticmethod and classmethod types, respectively. Static methods are defined without self arguments, and can be called directly on the class itself. Class methods are defined with a self-like parameter normally called cls/ You an call class methods directly on the class object too, but the cls parameter then automatically is bound to the class.
- Any function that contains a yield statement is called a generator. Each time a value is yielded (with yield), the function freezes: That is, it stops its execution at exactly that point and waits to be reawakened. When it is, it resumes its execution at the point where it stopped.
- A generator is a function that contains the keyword yield. When it is called, the code in the function body is not executed. Instead, an iterator is returned. Each time a value is requested, the code in the generator is executed until a yield or a return is encountered.
- To find out what a module contains, you can use dir function, which lists all the attributes of an object.
- When you look up an element in a shelf object, the object is reconstructed from its stored version; and when you assign an element to a key, it is stored.
- The match function will report a match if the pattern matches the beginning of a string; the pattern is not required to match the entire string.
- When you use binary mode, Python gives you exactly the contents found in the file.
- Xreadlines works almost like readlines except that it doesn’t read all the lines into a list.
- The syntax print >> file, text prints the text to the given file object
- You can create a connection directly to a database file – which will be created if it doesn’t exist—by supplying a file name.
- A socket is basically an “information channel” with a program on both ends
- A server socket uses its bind method followed by a call to listen to given address. A client socket can then connect to the server by using its connect method with the same address as used in bind.
- Urlretrieve returns a tuple(filename, headers), where filename is the name of the local file(this name is created automatically by urllib), and headers contains some information about the remote file.
- Screen scraping is a process whereby your program downloads Web pages and extracts information from them. Conceptually, the technique is very simple. You download the data and analyze it, you could, simply use urllib, get the Web page’s HTML source, and then use regular expressions or some such to extract the information.
- if you define methods called startup and teardown, they will be executed before and after each of the test methods, so you can use them to provide common initialization and cleanup code.
- The call to renderPDF.drawToFile saves your PDf file in the current directory
- A SAX parser reads through the XML file and telss you what it sees(text, tags, attributes), storing only small parts of the document at a time; this makes SAX simple, fast, and memory-efficient; DOM constructs a data structure (the document tree), which represents the entire document. This is slower and requires more memory, but can be useful if you want to manipulate the structure of your document
- The set_teminator method is used to set the line terminator to “\r\n”, which is the commonly used line terminator in network protocols
- SimpleXMLRPCSever instantiated with a tuple of the form (servername, port). The server name is the name of the machine on which the server will run (you can use an empty string here to indicate localhost), the port number can be any port you have access to.
- List.append(object) equivalent to list[len(list):len(list)] = [object]
- List.extend(sequence) equivalent to list[len(list):len(list)] = sequence
- Dict.fromkeys(seq[, val]) returns a dictionary with keys from seq and values set to val (default None)
- Dict.setdefault(key[, default]) rerurns dict[key] if it exists; otherwise it returns the given default value (default None) and binds dict[key] to it.
- The return statement halts the execution of a function and returns a value. If no value is supplied, None is returned.
- The yield statement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for loops