#!/usr/bin/python import inspect class Chomper(object): def __str__(self): s = '' try: frame = inspect.currentframe().f_back f = open(frame.f_code.co_filename, 'r') lines = f.readlines(frame.f_lineno) for i in xrange(frame.f_lineno, frame.f_code.co_firstlineno - 1, -1): line = lines[i].lstrip() if line.startswith('for '): fore = line.index(' ') + 1 aft = fore + line[fore:].index(' ') varname = line[fore:aft] if frame.f_locals.has_key(varname): s = frame.f_locals[varname] if s.endswith('\r\n'): s = s[:-2] elif s.endswith('\r') or s.endswith('\n'): s = s[:-1] break finally: del frame return s chomp = Chomper() def test(): for line in ('blargh\n', 'something', 'something else\n'): print chomp if __name__=="__main__": test()