def strip_comments(inStr): stringLiteral = False for i in xrange(len(inStr)): if inStr[i] == "\"" and (i == 0 or inStr[i - 1] != "\\"): stringLiteral = not stringLiteral elif not stringLiteral and inStr[i] == "#": return inStr[:i] return inStr print strip_comments('Hello. "This is not a # comment", but # this is')