I have a file named numbers.txt that looks something like this:
1243#74656453634#6356#56456456#565#1212121#78384
83#457#090#720347###24273#18712#478230478#57117
58125671#47464#74647#46474647#19192938#828##2583
5#2948284#6010203040#
I need to replace all of the '#' symbols with '!'. Then I need to replace 3 of the'!' symbols to '@' but not knowing which ones. It could be the 2nd, 5th, 15th or 1st, 6th, 8th, or......etc. What I need is some kind of loop, I guess, that will try replacing the positions as it goes: try replacing positions 1,2,3 then check the file, if not the correct replacements, try 1,2,4 check and if not correct then try 1,2,5 etc until all combinations are checked. I have this which will accomplish some of it....it will replace all of the '#' with '!' and I can get it to replace certain positions with a posList = [1,2,3].
def replace_pos(s, old, new, posList):
idx = -1
count = 0
while True:
"""
s.find() returns the position of the substring.
When the end of string is reached and no more
occurrances of substring are found, s.find()
returns -1.
"""
idx = s.find(old, idx+1)
count += 1
if idx == -1:
return s
elif count in posList:
s = "%s%s%s" % (s[:idx],new,s[(idx+len(old)):])
f = open("numbers.txt","r")
s = f.read()
s1 = s.replace("#","!")
oldStr = "!"
newStr = "@"
posList = [1,2,3]
s2 = replace_pos(s1, oldStr, newStr, posList)
print s2
The problem is that I don't want to do something like this:
comb_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,4,5], [2,3,4], [3,4,5]]
for clist in comb_list:
s1 = replace_pos(s, oldStr, newStr, clist)
because of all of the possible combinations I'd have to enter in the comb_list. Isn't there an easier way to do this? Besides it doesn't quite accomplish my goals.