title: Python: Find the longest word in a string
body: <p>I'm preparing for an exam but I'm having difficulties with one past-paper question. Given a string containing a sentence, I want to find the longest word in that sentence and return that word and its length. <strong>Edit:</strong> I only needed to return the length but I appreciate your answers for the original question! It helps me learn more. Thank you.</p>
  
  <p>For example: string = "Hello I like cookies". My program should then return "Cookies" and the length 7.</p>
  
  <p>Now the thing is that I am not allowed to use any function from the class String for a full score, and for a full score I can only go through the string once. I am not allowed to use string.split() (otherwise there wouldn't be any problem) and the solution shouldn't have too many for and while statements. The strings contains only letters and blanks and words are separated by one single blank.</p>
  
  <p>Any suggestions? I'm lost i.e. I don't have any code.</p>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT</strong>: I'm sorry, I misread the exam question. You only have to return the length of the longest word it seems, not the length + the word.</p>
  
  <p><strong>EDIT2</strong>: Okay, with your help I think I'm onto something...</p>
  
  <pre><code>def longestword(x):
        alist = []
        length = 0
        for letter in x:
               if letter != " ":
                       length += 1
               else:
                       alist.append(length)
                       length = 0
        return alist
  </code></pre>
  
  <p>But it returns [5, 1, 4] for "Hello I like cookies" so it misses "cookies". Why? EDIT: Ok, I got it. It's because there's no more " " after the last letter in the sentence and therefore it doesn't append the length. I fixed it so now it returns [5, 1, 4, 7] and then I just take the maximum value.</p>
  
  <p>I suppose using lists but not .split() is okay? It just said that functions from "String" weren't allowed or are lists part of strings?</p>