Skip to content

Instantly share code, notes, and snippets.

@emptypage
Created March 1, 2015 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emptypage/76751c037a2d464204eb to your computer and use it in GitHub Desktop.
Save emptypage/76751c037a2d464204eb to your computer and use it in GitHub Desktop.
Iterate lines of the string from its tail to its top.
def iterlines_backword(s):
""" Iterate lines of `s` from its tail to its top.
>>> list(iterlines_backword('a'))
['a']
>>> list(iterlines_backword('a\\n'))
['a\\n']
>>> list(iterlines_backword('a\\nb'))
['b', 'a\\n']
>>> list(iterlines_backword('a\\nb\\n'))
['b\\n', 'a\\n']
>>> list(iterlines_backword('a\\nb\\nc'))
['c', 'b\\n', 'a\\n']
>>> list(iterlines_backword('a\\nb\\nc\\n'))
['c\\n', 'b\\n', 'a\\n']
>>> list(iterlines_backword('a\\n\\nb\\n'))
['b\\n', '\\n', 'a\\n']
>>> list(iterlines_backword('\\n'))
['\\n']
>>> list(iterlines_backword('\\na'))
['a', '\\n']
>>> list(iterlines_backword(''))
[]
"""
p = q = len(s)
while 1:
try:
p = s.rindex('\n', 0, q-1)+1
except ValueError:
break
yield s[p:q]
q = p
if q:
yield s[:q]
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment