search and replace

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ironmonkey69
    New Member
    • Jul 2007
    • 43

    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?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by ironmonkey69
    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:[code=Python]>>> def nthzero(numList , nth):
    ... outList = []
    ... for num in numList:
    ... if not num%nth:
    ... outList.append( 0)
    ... else:
    ... outList.append( num)
    ... return outList
    ...
    >>> nthzero(range(1 ,50),7)
    [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]
    >>> [/code]OR any list:[code=Python]def nthzero(numList , nth):
    outList = []
    for i, num in enumerate(numLi st):
    if not (i+1)%nth:
    outList.append( 0)
    else:
    outList.append( num)
    return outList


    numList = range(6,400,12)
    nth = 7

    print nthzero(numList , nth)
    print nthzero(['x']*30, nth)

    >>> [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]
    ['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']
    >>>[/code]

    Comment

    • ironmonkey69
      New Member
      • Jul 2007
      • 43

      #3
      what can I do if the numbers are not separated by commas?

      Comment

      • bartonc
        Recognized Expert Expert
        • Sep 2006
        • 6478

        #4
        Originally posted by ironmonkey69
        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.

        Please be specific in your questions.
        Thank you.

        Comment

        • cnobile
          New Member
          • Apr 2007
          • 6

          #5
          You can use a for loop like this.

          Code:
          numbers = range(0,2500) # Make list of numbers
          step = 5
          
          for num in range(numbers[0], numbers[-1], step):
          	numbers[num] = 0 # set to zero
          
          print numbers
          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].

          Comment

          Working...