Python Learning Summary
Python methods and module
1.String methods
-
strip()
Description
The method strip() returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Example:
str='0000str000aaa000' print str.strip('0')
Result :
'str000aaa'
2. re module
- re.search
re.
search
(pattern, string, flags=0)
return a corresponding match object, return None if not match pattern, group(0) return full match, group(1) return first match, group(2) return second match
Example:
import re m = re.search('(1).*','123') print m.group(0) print m.group(1)
Result:
'123'
'1'
- re.sub
re.
sub
(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string
\n
is converted to a single newline character, \r
is converted to a carriage return, and so forth. Unknown escapes such as \j
are left alone. Backreferences, such as \6
, are replaced with the substring matched by group 6 in the pattern. For example:
import re
print re.sub('\d','a','123')
Result:
'aaa'
- re.findall
re.
findall
(pattern, string, flags=0)
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. For example:
import re
print re.findall('12','12111222')
print re.findall('(1)(2)','12111222')
Result:
['12', '12']
[('1', '2'), ('1', '2')]