Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex (vim) for print ... to print(...) for python2 to python3

This post is helpful only if you have strings inside of the print command. Now I have tons of sourcecode with a statement such as

print milk,butter

which should be formatted to

print(milk,butter)

And capturing the end of the line with \n was not sucessfull. Any hints?

like image 296
varantir Avatar asked Mar 23 '14 11:03

varantir


3 Answers

I am not familiar with 2to3, but from all the comments, it looks like the correct tool for the job.

That said, perhaps we can use this question as an excuse for a short lesson in some vim basics.

First, you want a pattern that matches the correct lines. I think that ^\s*print\> will do:

  • ^ matches start of line (and $ matches end of line).
  • \s matches whitespace (space or tab)
  • * means 0 or more of the previous atom (as many as possible, or "greedy").
  • print is a literal string.
  • \> matches end-of-word (zero width). You might use a (literal) space or \s\+ instead.

Next, you need to identify the part to be enclosed in parentheses. Since * is greedy, .* will match to the end of the line; there is no need to anchor it on the right. Use \(\s*print\) and \(.*\) to capture the pieces, so that you can refer to them as \1 and \2 in the replacement.

Now, put the pieces together. There are many variants, and I have not tried to "golf" this one:

:%s/^\(\s*print\)\s\+\(.*\)/\1(\2)

Some people prefer the "very magic" version, where only a-z, A-Z, 0-9, and _ are treated as literal characters; then you do not need to escape the parentheses nor the plus:

:%s/^\v(\s*print)\s+(.*)/\1(\2)
like image 163
benjifisher Avatar answered Nov 10 '22 18:11

benjifisher


You could use 2to3 and only apply the fix for print statement -> print function.

2to3 --fix=print [yourfiles]

This should automatically handle all those strange cases which won't work with e.g. a vim regex.

If you are missing the 2to3 shell script for some reason, run the lib as a module:

python -m lib2to3 --fix=print [yourfiles]
like image 26
wim Avatar answered Nov 10 '22 20:11

wim


Since you're in vim already:

:!2to3 --fix=print --write %
like image 6
Tarrasch Avatar answered Nov 10 '22 20:11

Tarrasch