Skip to content

Instantly share code, notes, and snippets.

@brandonio21
Last active March 11, 2018 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonio21/fc3b780349684f069ae0949809112321 to your computer and use it in GitHub Desktop.
Save brandonio21/fc3b780349684f069ae0949809112321 to your computer and use it in GitHub Desktop.
Convert simple python for loops to while loops
"""
Super simple script to convert for loops to while loops
Usage:
$ python f2w.py
for i in [1,2,3]:
print(i)
^D
__i = 0
while __i < len([1,2,3]):
i = [1,2,3][__i]
print(i)
__i += 1
"""
import re
import textwrap
import sys
FOR_REGEX = re.compile(r'^(\s*)for\s+(\w+)\s+in\s+(\w+):(.+)',
flags=re.DOTALL | re.MULTILINE)
for_stmt = sys.stdin.read()
print(FOR_REGEX.sub(
r"\1__i = 0\n\1while __i < len(\3):\n \2 = \3[__i]\4 __i += 1",
for_stmt
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment