Created
March 1, 2015 10:34
-
-
Save emptypage/76751c037a2d464204eb to your computer and use it in GitHub Desktop.
Iterate lines of the string from its tail to its top.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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