First of all, many string functions – including strip and replace – are deprecated. The following answer uses string methods instead. (Instead of string.strip(" Hello ")
, I use the equivalent of " Hello ".strip()
.)
Here's some code that will simplify the job for you. The following code assumes that whatever methods you call on your string, that method will return another string.
class O(object):
c = str.capitalize
r = str.replace
s = str.strip
def process_line(line, *ops):
i = iter(ops)
while True:
try:
op = i.next()
args = i.next()
except StopIteration:
break
line = op(line, *args)
return line
The O
class exists so that your highly abbreviated method names don't pollute your namespace. When you want to add more string methods, you add them to O
in the same format as those given.
The process_line
function is where all the interesting things happen. First, here is a description of the argument format:
- The first argument is the string to be processed.
- The remaining arguments must be given in pairs.
- The first argument of the pair is a string method. Use the shortened method names here.
- The second argument of the pair is a list representing the arguments to that particular string method.
The process_line
function returns the string that emerges after all these operations have performed.
Here is some example code showing how you would use the above code in your own scripts. I've separated the arguments of process_line
across multiple lines to show the grouping of the arguments. Of course, if you're just hacking away and using this code in day-to-day scripts, you can compress all the arguments onto one line; this actually makes it a little easier to read.
f = open("parrot_sketch.txt")
for line in f:
p = process_line(
line,
O.r, ["He's resting...", "This is an ex-parrot!"],
O.c, [],
O.s, []
)
print p
Of course, if you very specifically wanted to use numerals, you could name your functions O.f1
, O.f2
, O.f3
… but I'm assuming that wasn't the spirit of your question.