Created
July 14, 2012 08:39
-
-
Save dingzhihu/3110069 to your computer and use it in GitHub Desktop.
python snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##string | |
ustring = u'A unicode \u018e string \xf1' | |
s = unistring.encode('utf-8') | |
t = unicode(s, 'utf-8') | |
##list | |
strs = ['ccc', 'aaaa', 'd', 'bb'] | |
print sorted(strs, key=len) ## ['d', 'bb', 'ccc', 'aaaa'] | |
##tuple | |
(x, y, z) = (42, 13, "hike") | |
print z ## hike | |
##list comprehensions | |
fruits = ['apple', 'cherry', 'bannana', 'lemon'] | |
afruits = [ s.upper() for s in fruits if 'a' in s ] | |
##dict | |
hash = {} | |
hash['word'] = 'garfield' | |
hash['count'] = 42 | |
s = 'I want %(count)d copies of %(word)s' % hash # %d for int, %s for string | |
##regular expression | |
match = re.search(r'iii', 'piiig') ##match.group() == "iii" | |
str = 'purple alice@google.com, blah monkey bob@abc.com blah dishwasher' | |
emails = re.findall(r'[\w\.-]+@[\w\.-]+', str) | |
for email in emails: | |
print email | |
##urllib | |
ufile = urllib.urlopen(url) | |
text = ufile.read() | |
info = ufile.info() | |
##os | |
os.listdir('.') | |
##cmds | |
(status, output) = commands.getstatusoutput(cmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment