Skip to content

Instantly share code, notes, and snippets.

@dingzhihu
Created July 14, 2012 08:39
Show Gist options
  • Save dingzhihu/3110069 to your computer and use it in GitHub Desktop.
Save dingzhihu/3110069 to your computer and use it in GitHub Desktop.
python snippets
##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