Iterate over a string 2 (or n) characters at a time in Python

后端 未结 12 1883
悲哀的现实
悲哀的现实 2020-11-30 07:27

Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like \"+c-R+D-E\" (there are a few extra letters).

12条回答
  •  一生所求
    2020-11-30 08:01

    from itertools import izip_longest
    def grouper(iterable, n, fillvalue=None):
        args = [iter(iterable)] * n
        return izip_longest(*args, fillvalue=fillvalue)
    def main():
        s = "+c-R+D-e"
        for item in grouper(s, 2):
            print ' '.join(item)
    if __name__ == "__main__":
        main()
    ##output
    ##+ c
    ##- R
    ##+ D
    ##- e
    

    izip_longest requires Python 2.6( or higher). If on Python 2.4 or 2.5, use the definition for izip_longest from the document or change the grouper function to:

    from itertools import izip, chain, repeat
    def grouper(iterable, n, padvalue=None):
        return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
    

提交回复
热议问题