subsections
Log
Coding
string
Lists and dictionaries
first, the log
#!/usr/bin/python
#-*-coding:utf-8-*-
' Created on
2013-4-26
@author: CHENLL
Log Level
NOTSET < DEBUG < info < WARNING < ERROR < CRITICAL
If the level of Looger is set to info, then logs less than info level are not output, greater than or equal to the info level output
'
Import logging
# Create a logger
logger = Logging.getlogger (' Log ')
logger.setlevel (logging. DEBUG)
# Creates a handler for writing to the log file
fh = logging. Filehandler (' Test.log ')
fh.setlevel (logging. DEBUG)
# Then create a handler for output to console
ch = logging. Streamhandler ()
ch.setlevel (logging. DEBUG)
# defines the output format for handler , Time-class name-rank name-log content
formatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ')
Fh.setformatter (Formatter)
Ch.setformatter (Formatter)
# Add handler
Logger.addhandler (FH)
logger.addhandler (CH) to logger
Record a log
logger.info (' Building table ')
Console and Test.log output:
2013-04-26 10:40:46,381-log-info-building Table
Second, coding
There are two types of strings in Python: One is a byte string and one is a Unicode string
The py file is ASCII encoded by default, and the Chinese will do an ASCII to system default encoding conversion when it is displayed: Syntaxerror:non-ascii character. You need to add an encoding instruction in the first or second line of the code file #coding=utf-8 all Chinese ex:myname= "Chen" will be declared as a utf-8 encoded byte string.
The General Python preset editor is ASCII, and if you need to change it, the action is as follows:
Importsys
Reload (SYS)
Sys.setdefaultencoding (' Utf-8 ')
The representation of strings inside Python is Unicode encoding, so in encoding conversions, Unicode is usually used as the intermediate encoding, i.e. decoding other encoded strings (decode) into Unicode and then encoding from Unicode (encode) into another kind of code. Therefore, it is important to understand first that the string STR is encoded, then decode into Unicode, and then encode the default encoding of the string in other coded code in accordance with the code file itself.
1. Unicode for any language text, is 1 characters and 1 encodings, so "hi!" is 3 Unicode characters, "Hello!" is also a 3 Unicode character.
2. UTF-8 uses 3 characters to represent 1 Chinese characters and 1 characters to represent English characters. So, "hi!" is 3 UTF-8 characters, "Hello!" is a 7 UTF-8 character.
3. GBK uses 2 characters to represent 1 Chinese characters and 1 characters to represent English characters. So, "hi!" is 3 GBK characters, "Hello!" is a 5 GBK character.
4. The Decode method, which is a method of any string, converts the string to Unicode format, and the parameter is the code name of the source string.
5. The Encode method, in which any string has a method, converts the string to the format specified by the parameter, which is the target code name.
Three, String common operation
#!/usr/bin/python #-*-coding:utf-8-*-' Created on 2013-4-30 @author: chenlly ' ' #复制字符串 #strcpy (SSTR1,SSTR2) sStr1 = ' strcpy ' sStr2 = sStr1 sStr1 = ' strcpy2 ' Print sStr2 #连接字符串 #strcat (sstr1,sstr2) sStr1 = ' strcat ' sStr2 = ' append ' sStr 1 + + sStr2 print sStr1 #查找字符 #strchr (SSTR1,SSTR2) # < 0 for not found sStr1 = ' strchr ' sStr2 = ' ch ' NPOs = Sstr1.index (SSTR2) p Rint NPOs #查找字符串 #strchr (sstr1,sstr2) sStr1 = ' ABCDEFG ' sStr2 = ' cde ' Print Sstr1.find (SSTR2) #扫描字符串是否包含指定的字符 #strspn (SS TR1,SSTR2) sStr1 = ' 12345678 ' sStr2 = ' 456 ' Print len (SSTR1 and SSTR2) #比较字符串 #strcmp (sstr1,sstr2) #sStr1 = = sstr2:0 #sSt R1 > Sstr2:1 #sStr1 < sstr2:-1 sStr1 = ' strchr ' sStr2 = ' strch ' Print cmp (SSTR1,SSTR2) #字符串长度 #strlen (SSTR1) sStr1 = ' strlen ' Print len (sStr1) #将字符串中的大小写转换 #strlwr (sStr1) sStr1 = ' jcstrlwr ' sStr1 = Sstr1.upper () sStr1 = Sstr1.lower () pr int sStr1 #追加指定长度的字符串 #strncat (sstr1,sstr2,n) sStr1 = ' 12345 ' sStr2 = ' abcdef ' n = 3 sStr1 + = sstr2[0:n] Print sStr1 #字符 String specified length comparison #strncmp (sstr1,sstr2,n) sStr1 = ' 12345 ' sStr2 = ' 123BC ' n = 3 print cmp (SSTR1[0:N],SSTR2[0:N)) #复制指定长度的字符 #strncpy (sstr1,sstr2,n) sStr1 =
' sStr2 = ' 12345 ' n = 3 sStr1 = sstr2[0:n] Print sStr1 #将字符串前n个字符替换为指定的字符 #strnset (sstr1,ch,n) sStr1 = ' 12345 ' ch = ' R ' n = 3 sStr1 = n * ch + sstr1[3:] Print sStr1 #扫描字符串 #strpbrk (sstr1,sstr2) sStr1 = ' Cekjgdklab ' sStr2 = ' gka ' NPOs =-1 F
or C in sstr1:if C in sstr2:npos = Sstr1.index (c); Print NPOs #翻转字符串 #strrev (sStr1) sStr1 = ' ABCDEFG ' sStr1 = sstr1[::-1] Print sStr1 #分割字符串 #strtok (sstr1,sstr2) sStr1 = ' Ab,cde,fgh,ijk ' sStr2 = ', ' sStr1 = Sstr1[sstr1.find (SSTR2) + 1:] Print sStr1 #或者 s = ' Ab,cde,fgh,ijk ' Print (S.split (', ') #连接字符串 delimiter = ', ' mylist = [' Brazil ', ' Russia ', ' India ', ' ', '] print delimiter.join (mylist) #只显示字母与数字 def only
CharNum (s,oth= '): S2 = S.lower (); Fomart = ' abcdefghijklmnopqrstuvwxyz0123456789 ' for C in S2:if not C in fomart:s = S.replace (c, '
');
return s; Print(Onlycharnum ("China a000 Aa-b")
four, dictionaries and lists
Dict
Data is stored in the form of a key-value pair (key-value). Python hash function operations, based on the results of the calculation of the value of the storage address, so the dictionary is stored in disorder, and the key must be hashed. The hash indicates that the key must be an immutable type, such as a number, a string, a tuple containing only immutable type elements (1,2,3, ' abc ')
Len (a) |
Get the number of elements in dictionary a |
A[K] |
Gets the value of the key k in dictionary a |
A[k] = V |
Set the value of the key k in dictionary a as V |
Del A[k] |
Use key to remove separate elements from a dictionary. For example, delete user= ' root ' in dictionary dic: del dic[' user ' |
A.clear () |
Clears all elements from a dictionary. For example, delete all elements in dictionary dic: Dic.clear () |
A.copy () |
Get a copy of the dictionary |
K in a |
There is a key k in the dictionary returns True and no returns false |
K Not in a |
Key k does not exist in the dictionary returns True, otherwise returns false |
A.has_key (k) |
Determine if the dictionary a contains key k |
A.items () |
Get the key-value pair list in dictionary a |
A.keys () |
Get the list of the keys in dictionary a |
A.update ([b]) |
Update a dictionary from the B dictionary and append if the key is the same if it is not present in a. |
A.fromkeys (seq[, value]) |
Creates a new dictionary with keys from SQL, values from value |
A.values () |
Get the list of the values in dictionary a |
A.get (k[, X]) |
Remove the value of the key k from dictionary A and if not, return X |
A.setdefault (k[, X]) |
Set the value of the key to K to the default value x. If k is present in dictionary A, the value of K is returned, and if not, add a K-x key value pair to the dictionary and return the value X |
A.pop (k[, X]) |
Remove the value of key k in dictionary A and delete it from dictionary A, if there is no key k in dictionary A, return value X |
A.popitem () |
Remove the key-value pair from dictionary A and delete it from dictionary a |
A.iteritems () |
Returns the iterator for all key-value pairs in dictionary a. |
A.iterkeys () |
Returns the iterator for all keys in dictionary a. |
A.itervalues () |
Returns an iterator for all values in dictionary a. |
List
A Collection object (set) in Python is a set of unordered, hashed values that contain two types: mutable sets (set) and immutable sets
Frozenset, so the set is not hashed, the Frozenset is hashed and can be used as a dictionary key.
#!/usr/bin/python #-*-coding:utf-8-*-' Created on 2013-4-21 @author: chenlly ' def disPlay (
DICT): For key in Dict:print key + "," + Dict[key] def dicfun (): #dict2 = Dict (); Dict2 = {' name ': ' Chen ', ' Port ': ' 8809 '} #遍历字典 display (dict2) print '---end display---' #新增数据项 dict2[' IP '
= ' 198.164 ' Display (dict2) print '---end add---' #修改数据项 dict2[' name ' = ' Laoben ' Display (DICT2) print '---end edit---' #删除已经存在的数据项 del dict2[' name ' "DisPlay (dict2) print '---end remove---' de
F Main (): Dicfun ();
if __name__ = = "__main__": Main ();