472,992 Members | 3,283 Online

# search and replace

is there a way that I can search for every nth term sucha as a number ranging from 0-2500 and replacing them with zeroes?
Jul 19 '07 #1
4 1355
bvdet
2,851 Expert Mod 2GB
is there a way that I can search for every nth term sucha as a number ranging from 0-2500 and replacing them with zeroes?
In a list of numbers in sequence:
Expand|Select|Wrap|Line Numbers
1. >>> def nthzero(numList, nth):
2. ...     outList = []
3. ...     for num in numList:
4. ...         if not num%nth:
5. ...             outList.append(0)
6. ...         else:
7. ...             outList.append(num)
8. ...     return outList
9. ...
10. >>> nthzero(range(1,50),7)
11. [1, 2, 3, 4, 5, 6, 0, 8, 9, 10, 11, 12, 13, 0, 15, 16, 17, 18, 19, 20, 0, 22, 23, 24, 25, 26, 27, 0, 29, 30, 31, 32, 33, 34, 0, 36, 37, 38, 39, 40, 41, 0, 43, 44, 45, 46, 47, 48, 0]
12. >>>
OR any list:
Expand|Select|Wrap|Line Numbers
1. def nthzero(numList, nth):
2.     outList = []
3.     for i, num in enumerate(numList):
4.         if not (i+1)%nth:
5.             outList.append(0)
6.         else:
7.             outList.append(num)
8.     return outList
9.
10.
11. numList = range(6,400,12)
12. nth = 7
13.
14. print nthzero(numList, nth)
15. print nthzero(['x']*30, nth)
16.
17. >>> [6, 18, 30, 42, 54, 66, 0, 90, 102, 114, 126, 138, 150, 0, 174, 186, 198, 210, 222, 234, 0, 258, 270, 282, 294, 306, 318, 0, 342, 354, 366, 378, 390]
18. ['x', 'x', 'x', 'x', 'x', 'x', 0, 'x', 'x', 'x', 'x', 'x', 'x', 0, 'x', 'x', 'x', 'x', 'x', 'x', 0, 'x', 'x', 'x', 'x', 'x', 'x', 0, 'x', 'x']
19. >>>
Jul 19 '07 #2
what can I do if the numbers are not separated by commas?
Jul 19 '07 #3
bartonc
6,596 Expert 4TB
what can I do if the numbers are not separated by commas?
Your question lacks specificity. Perhaps you are wanting to work with text?
Maybe that text is broken up with newline character, maybe not.
You may even need help reading a text file into memory.

Thank you.
Jul 19 '07 #4
cnobile
6 Nibble
You can use a for loop like this.

Expand|Select|Wrap|Line Numbers
1. numbers = range(0,2500) # Make list of numbers
2. step = 5
3.
4. for num in range(numbers[0], numbers[-1], step):
5.     numbers[num] = 0 # set to zero
6.
7. print numbers
8.
This will work with text or numbers. First put your objects in a list. In the case of text use 0 instead of numbers[0] and the result of len(text) for numbers[-1].
Jul 19 '07 #5