- 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'