Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python replace print with function

Tags:

python

I'm using python 2.6 and have a bunch of print statments in my long program. How can I replace them all with my custom print function, lets call it scribble(). Because if I just search and replace print with scribble( there is no closing parentesis. I think regular expressions is how, but I have experimented with them for a day or so and I can't seem to get it to work.

like image 208
captainandcoke Avatar asked May 11 '12 21:05

captainandcoke


People also ask

How do you override print in Python?

Approach. By default, Python's print statement ends each string that is passed into the function with a newline character, \n . This behavior can be overridden with the function's end parameter, which is the core of this method. Rather than ending the output with a newline, we use a carriage return.

How do I replace an old print statement in Python?

Simple Version. One way is to use the carriage return ( '\r' ) character to return to the start of the line without advancing to the next line.

What is print function in Python?

Python print() Function The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


2 Answers

Using Pycharm

If you are using pycharm, you can use Regex function by this pattern:

Replace: print\s(.*)
With: print($1)

enter image description here

like image 192
Alvin Avatar answered Oct 24 '22 23:10

Alvin


Using editor

I don't know which editor you're using, but if it supports RegEx search and replace, you can try something like this:

Replace: print "(.*?)"
With: scribble( "\1" )

I tested this in Notepad++.

Using Python

Alternatively, you can do it with Python itself:

import re

f = open( "code.py", "r" )
newsrc = re.sub( "print \"(.*?)\"", "scribble( \"\\1\" )", f.read() )
f.close()

f = open( "newcode.py", "w" )
f.write( newsrc )
f.close()
like image 27
Overv Avatar answered Oct 25 '22 00:10

Overv