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

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

    Here's my answer, a little bit cleaner to my eyes:

    for i in range(0, len(string) - 1):
        if i % 2 == 0:
            print string[i:i+2]
    

提交回复
热议问题