title: Finding longest string in numerical order in a string in Python
body: <p>I have a string with thousands of number in it. I need to go through the string and find the longest set of characters that are in numerical order. For example:</p>
  
  <pre><code>string = '1223123341223455'
  </code></pre>
  
  <p>The longest string of characters in that string in numerical order is 1223455 and it is 7 characters long. Here is an example of what I have at the moment:</p>
  
  <pre><code>r=r2=''
  a=b=0
   while a &lt; len(string)+1:
      if string[a] &lt;= string[b]:
          r += string[a]
      else:
          if len(r) &lt; len(r2):
              r = r2
      a += 1
      b += 1
  </code></pre>
  
  <p>With this it tells me that the string index is out of range on the line:</p>
  
  <pre><code>if string[a] &lt;= string[b]
  </code></pre>
  
  <p>Here is my logic: Check to see if the first number is less than or equal to the second number. If it is, those two numbers are in numerical order. Add that first number to an empty string. Keep doing this until you run into a point when the first number is greater than the second number. After this point is reached, save what you have as a string and continue where you left off, except this time concatenate the number you accumulate to a different string. After you have two strings of numbers, compare the two and take the higher one. Continue this until you are done processing the string. I hope this makes sense, kind of hard to explain.</p>