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

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

    Maybe this would be cleaner?

    s = "+c-R+D-e"
    for i in xrange(0, len(s), 2):
        op, code = s[i:i+2]
        print op, code
    

    You could perhaps write a generator to do what you want, maybe that would be more pythonic :)

提交回复
热议问题