def _split(line): part = "" line = list(line) while line: s = line.pop(0) if s != ';': part += s if s == '"': prev = '' while line: s = line.pop(0) part += s if s == '"' and prev != '\\': break prev = s continue else: yield part part = "" yield part def parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ plist = [x.strip() for x in _split(line)] key = plist.pop(0).lower() pdict = {} for p in plist: i = p.find('=') if i >= 0: name = p[:i].strip().lower() value = p[i+1:].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace('\\\\', '\\').replace('\\"', '"') pdict[name] = value return key, pdict test = '''Content-Disposition: form-data; name="_media"; filename="Demo; 28.07.2006.jpg" ''' print test print parse_header(test)