Note that there are some explanatory texts on larger screens.

plurals
  1. POComparing characters in a string sequentially in Python
    text
    copied!<p>I am trying to figure out how to compare a character in a string to the next character in the string. For example, if I have a string:</p> <pre><code>s = 'vzcbotdebobeggglakyl' </code></pre> <p>I want to be able to compare the first character with the second character, and if the second character is greater than or equal to the first character (alphabetically speaking, a &lt; b, g > e, y = y, etc) I want to add 1 to another variable (Basically a counter). If it isn't, I want to reset the counter to 0. And basically repeat the entire process for the length of the string. If the counter becomes greater than the maxlen variable, then add one to maxlen (Or make maxlen = sublen). My attempt so far is (And I think it is working):</p> <pre><code>s = 'vzcbotdebobeggglakyl' sublen = 1 maxlen = 0 startnum = 0 for char in s: stopnum = startnum + 1 if stopnum &lt; len(s): charone = s[startnum] chartwo = s[stopnum] if charone &lt;= chartwo: sublen += 1 startnum += 1 if sublen &gt; maxlen: maxlen = sublen else: startnum +=1 sublen = 1 else: sublen = 0 print 'Longest substring is', maxlen, 'characters.' </code></pre> <p>Now, what I also would like to do is have a line print out that substring of characters. I have been working on this for five hours and can't get it right. I have tried so many different things that I am basically confused even worse now than when I started. In the above example, I want it to say</p> <pre><code>Longest substring is begggl, which is 6 characters. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload