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

后端 未结 12 1908
悲哀的现实
悲哀的现实 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 07:54

    Triptych inspired this more general solution:

    def slicen(s, n, truncate=False):
        assert n > 0
        while len(s) >= n:
            yield s[:n]
            s = s[n:]
        if len(s) and not truncate:
            yield s
    
    for op, code in slicen("+c-R+D-e", 2):
        print op,code
    

提交回复
热议问题