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.
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.
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.
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.
Using Pycharm
If you are using pycharm, you can use Regex function by this pattern:
Replace: print\s(.*)
With: print($1)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With