Iterate over the lines of a string

前端 未结 6 1785
情深已故
情深已故 2020-11-28 03:15

I have a multi-line string defined like this:

foo = \"\"\"
this is 
a multi-line string.
\"\"\"

This string we used as test-input for a par

6条回答
  •  春和景丽
    2020-11-28 04:07

    I suppose you could roll your own:

    def parse(string):
        retval = ''
        for char in string:
            retval += char if not char == '\n' else ''
            if char == '\n':
                yield retval
                retval = ''
        if retval:
            yield retval
    

    I'm not sure how efficient this implementation is, but that will only iterate over your string once.

    Mmm, generators.

    Edit:

    Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.

提交回复
热议问题