0

Is there any way to search and replace certain strings, but also watch out for similar strings, and not replace those?

for example, if i have

self.a
self.b
self.c
self.d
self.e
self.f
self.g

and i wanted

self.a
self.__b
self.c
self.__d
self.__e
self.f
self.g

and i want to add __ to some of the variables to make them private, but not others, how would i do it, short of changing each individually, or changing all of them and then undoing the ones i dont want? my program has a large number of variables and uses each of them very often, so i dont want to go through the code myself.

1
  • 3
    Isn't this an editing problem more than a Python problem? For example, you could use your editor to replace all "self.b" with "self.__b", or use sed in a similar way. Commented Jan 6, 2011 at 18:39

4 Answers 4

3

Regular expressions?

Python's re module has a function called re.sub which will replace everything matching a pattern with something else.

You can also use regular expressions from Perl, awk, sed, etc. depending on your preferences. Just search and replace based on whatever patterns you might want to match and change.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for sed. A one-liner would probably work and be easier than writing a Python script.
1

Back up your script. Create a new script and import re, then re.sub() your original script. Run a unit test on the regex'd script to ensure functionality.

Comments

1

In addition to creating another script to perform the replacement, you can probably do this in your editor. For example if you use Vim typing the following should do what you want:

:%s/self\.\(b\|d\|e\)/self.__\1/g

1 Comment

If you don't use Vim, but use a Unix/Linux command line, try sed 's/self\.\(b\|d\|e\)/self.__\1/g' your_python_module.py
1

Regular expressions are your friend here. They are a little intensive to the beginner, though. To accomplish the goal in the above example use the python command:

import re
pattern = r'(self\.)(b|d|e)\s'
result = re.sub(pattern, '\1__\2', source)

This takes every instance of a string starting with 'self.' followed by b, d, or e, and replaces it with a 'self.__' followed by the correct string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.