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

后端 未结 12 1913
悲哀的现实
悲哀的现实 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
    2020-11-30 07:51

    I ran into a similar problem. Ended doing something like this:

    ops = iter("+c-R+D-e")
    for op in ops
        code = ops.next()
    
        print op, code
    

    I felt it was the most readable.

提交回复
热议问题