Skip to content

Instantly share code, notes, and snippets.

@tuxfight3r
Forked from franzwong/python_cheatsheet.md
Created March 13, 2016 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuxfight3r/c178dbecc80415ccaaa5 to your computer and use it in GitHub Desktop.
Save tuxfight3r/c178dbecc80415ccaaa5 to your computer and use it in GitHub Desktop.
Python cheatsheet

Python cheatsheet

  • for loop
for i in xrange(10):
  print i
  • while loop
count = 0
while (count < 9):
  print i
  count += 1
  • exception handling
try:
  raise Exception('invalid password')
except Exception, e:
  print 'error occurs, reason : %s' % e
import traceback

try:
  raise Exception('invalid password')
except Exception, e:
  traceback.print_exc()
  • class
class Button:
    def __init__(self):
        self.pressed = False
    def press(self):
        self.pressed = not self.pressed

button = Button()
button.press()
  • display local date time
import time

format = '%Y-%m-%d\'T\'%H:%M:%S'
now = time.localtime()
str = time.strftime(format, now)
print(str)
  • regular expression

simple matching

import re

pattern = r'^blog/admin/(?:list/)?$'
str = 'blog/admin/list/'

reObj = re.compile(pattern)
if reObj.match(str):
  print 'match'
else:
  print 'not match'
import re

patter = '\[(.*)\]\n'
str = '[Apple]\n[Orange]\n[Banana]\n'

for m in re.finditer(patter, str):
  print m.group(1) # print out 'Apple', 'Orange', 'Banana'
import re

pattern = '\[(.*)\]\n'
before = '[Apple]\n[Orange]\n[Banana]\n'

after = re.sub(pattern, '{\\1}\n', before)
print after # print out '{Apple}\n{Orange}\n{Banana}\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment