17

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?

3
  • 4
    As InspectorG4dget said on the linked question: use 2to3 Commented Mar 23, 2014 at 11:22
  • Hint: You wouldn't capture the end of line with \n, you'd capture it with $. Commented Mar 23, 2014 at 11:24
  • jonrsharpe: Just assume I can only use vim Commented Mar 23, 2014 at 13:47

3 Answers 3

14

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Fix the print in current line by pressing F3 (shortcut for "f*** python 3): nmap <F3> :s/^\(\s*print\)\s\+\(.*\)/\1(\2)<cr> . Note: the regex is not suitable for converting a large amount of code, just for correcting the occasional mistake when you work with both python2 and python3 code.
12

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]

Comments

6

Since you're in vim already:

:!2to3 --fix=print --write %

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.