Regular expression

import re
re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
# ['foot', 'fell', 'fastest']
re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10')
# [('width', '20'), ('height', '10')]

re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
       r'static PyObject*\npy_\1(void)\n{',
       'def myfunc():')
# 'static PyObject*\npy_myfunc(void)\n{'

String

Template

from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
# 'tim likes kung pao'
d = dict(who='tim')
Template('Give $who $100').substitute(d)
# ValueError: Invalid placeholder in string: line 1, col 11
Template('$who likes $what').substitute(d)
# KeyError: 'what'
Template('$who likes $what').safe_substitute(d)
'tim likes $what'

File paths

from pathlib import Path
p = Path('C:\\Program Files\\Internet Explorer\\iexplore.exe')
str(p.parent)
#'C:\\Program Files\\Internet Explorer'

Dictionary

Check if key exists


Fruits = {'a': "Apple", 'b':"Banana", 'c':"Carrot"}
key_to_lookup = 'a'
# Use .has_key()
if Fruits.has_key(key_to_lookup):
  print "Key exists"

# Use if-in
if key_to_lookup in Fruits:
  print "Key exists"