Strings
>>> s = ' Django is cool ' >>> words = S.split () >>> words[' Django ', ' is ', ' cool ']>>> '. Join (words) ' Django is cool ' >>> s.count (' o ') 3>>> s.find (' Go ') 4>>> s.replace (' Django ', ' Python ') ' Python is cool '
Some of the commonly used string functions:
String method |
Description |
count |
number of occurrences of Substring in string |
find |
Search for substring [also see index, RFind, Rindex] |
Join |
Merge substrings to single delimited string |
replace |
S Earch and replace (sub) string |
split |
split delimited string to substrings [also see SP Litlines] |
startswith |
Does string start with substring [also see endswith] |
Strip |
Remove leading and trailing whitespace [also see Rstrip, Lstrip] |
title |
title-case string [Also see capitalize, Swapcase] |
Upper |
uppercase string [also see lower] |
isupper |
is the string all uppercase? [Also see islower, and so forth] |
Formatted output:
>>> '%s is number%d ' percent (' python ', 1) ' Python is number 1 ' >>> hi = ' hellobaby ' >>> hi ' hello\n Baby ' >>> print Hihellobaby
Tuples
The elements inside a tuple cannot be modified, which is related to its own implementation mechanism, and it is a good choice to pass parameters if you do not want them to be modified.
>>> a = (' One ', ' one ') >>> a[0] ' one ' >>> c = (' Only ',) >>> c[0] "only" >>> d = ' on Ly ',>>> d[0] ' only '
It is important to note that when declaring a tuple, the key is a comma, and if not the following example is just a string, note that this is significant because many Django data types use a tuple:
>>> B = (' Only ') >>> b[0] ' o '
Dictionaries
A dictionary is a list of a sort of hash table with elements that have key and value two attributes. The elements of a dictionary can be modified, unordered, and size can vary. Such as:
>>> book = {' title ': ' Django ', ' Year ':2008}>>> ' title ' in Booktrue>>> book.get (' Pub ', ' N/a ') ' N/A ' >>> book[' pub '] = ' addision ' >>> book.get (' Pub ', ' N/A ') ' Addision ' >>> for key in book:...< C0/>print key, ': ', book[key]...year:2008title:djangopub:addision
Some common functions:
Dictionary Method |
Description |
|
Keys |
Keys (also see Iterkeys) |
|
Values |
Values (also see itervalues) |
|
Items |
Key-value pairs (also see ITERITEMS) |
|
Get |
Get value given key else default [also see SetDefault, Fromkeys] |
|
Pop |
Remove key from Dict and return value [also see clear, Popitem] |
|
Update |
Update Dict with contents of (a) other dict |
|
Enumerate
>>> data = Enumerate ((123, ' abc ', ' Hello ') >>> for I, value in data: ... Print I, Value ... 0 1231 ABC2 Hello
Exception Handling
If you try to open a file with exception handling:
Try: f = open (filename, ' r ') except IOError, E: return False, str (e)
You can also put a variety of error types into a tuple, one-off detection:
Try: Process_some_data () except (TypeError, ValueError,...), E: print "ERROR", E
Of course, different types of exceptions can be handled differently, and in the last case a exception is usually added, as this can include all the exception conditions:
Try: ... except (TypeError, ValueError), E: ... except Arithmeticerror, E: ... except Exception, E: ...
Files
>>> f = open (' Test.txt ', ' W ') >>> f.write (' foo\n ') >>> f.write (' bar\n ') >>> f.close ( ) >>> f = open (' Test.txt ', ' R ') >>> for line in F: ... Print Line.rstrip () ...foobar>>> f.close ()
Anonymous Functions
The anonymous function uses the keyword, which consists of lambda
an expression that represents the return value of the function. The usual way to use:
Lambda args:expression
Sorted (list_of_people, key = Lambda person:person.last_name) # equivalent to Def get_last_name (person): return Person.last_ Namesorted (list_of_people, key = Get_last_name)
* Args and * * Kwargs
Python inside the * is not a C language inside the pointer, as a parameter when passed, * represents a tuple (list), * * Represents dict
Examples are as follows:
def check_web_server (host, port, path): ...
General usage when calling a function:
Check_web_server (' 127.0.0.1 ', 8080, '/admin/')
If the parameter is used as a tuple or dict, the parameter can be passed in the form of a subscript, but it is very convenient to complete the parameters in the way of *:
Host_info = (' www.python.org ', +, '/') Check_web_server (host_info[0],host_info[1], host_info[2]) check_web_server (* Host_info) Host_info = {' host ': ' www.python.org ', ' Port ': ', ' path ': '/'}check_web_server (**host_info)
Dynamic instantiation
Unlike some of the other programming languages, Python supports dynamic instantiation of classes, such as:
>>> class Book (object): ... def __init__ (self, name): ... Self.name = name...>>> John = Book (' John ') >>> john.father = ' Jack ' >>> print John.fatherjack
Python Fundamental for Django