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

后端 未结 12 1915
悲哀的现实
悲哀的现实 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 08:06

    Great opportunity for a generator. For larger lists, this will be much more efficient than zipping every other elemnent. Note that this version also handles strings with dangling ops

    def opcodes(s):
        while True:
            try:
                op   = s[0]
                code = s[1]
                s    = s[2:]
            except IndexError:
                return
            yield op,code        
    
    
    for op,code in opcodes("+c-R+D-e"):
       print op,code
    

    edit: minor rewrite to avoid ValueError exceptions.

提交回复
热议问题