Tuesday 20 June 2017

Running python code from Vim and replacing the code with output

It is possible to write python code in vim and then execute the code. The output of the code will be placed in place of the python code. Let me illustrate you an example so that it becomes more clear.

Example:
Suppose that you have a string "Lavish" and you want to put each character of this string into a new line. We can write python code to do this.

for i in "Lavish":
    print i

Now select the above two lines by going in visal mode and then execute the following commmand:
:'<,'>!python

This will replace the python code with following lines:
L
a
v
i
s
h

Now, you may not see the real difference when the string is small, but as the string goes bigger, the power of vim becomes more visible.

Similarly, as an another example, say you want to print the following thing in a text file

1 Lavish
2 Lavish
3 Lavish
4 Lavish
5 Lavish

I'm sure, you must have figured it out that the python code for this will be:

for i in range(1,6):
    print str(i)+" Lavish"

and then follow the same thing again as described above. Similarly to the above mentioned examples, there is a lot of cool stuff that you can try out and make yourself more productive and efficient.

I hope this was interesting and you learned something from this. :)

No comments:

Post a Comment