Python Forum

Full Version: slicing words in a while loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
I've almost got this assignment figured out but now I'm stuck.

The assignment involves prompting the user for a set of words, then the program counts and prints the individual word and the number of letters in each word.

I'm NOT allowed to use split().

I have two variables keeping track of where the words are: left and right

When I run this, it works until the last word and then it doesn't know what to do when right hunts for the next space, there isn't one because it's the end of the list of words.

My teacher puts a lot of emphasis on keeping things simple and he doesn't like it when we get too "pythony", because he's trying to teach us programming in general, not just with python.

words = input('Enter a series of words with spaces in between: ')
print('The length of the input is ',len(words))

wordCount = 0
left = 0
right = 0

while left < len(words):
    
     
    if ' ' not in words[right:]:
        break
           

    elif left >= right:

        right = words.find(" ", left)
        wordCount = wordCount + 1
        length = right - left + 1
        print('len = ',length, words[left:right])
        print(left, right)
        left = right + 1

    else:
        left < right
        left = left + 1
        
print('There are ' , wordCount, ' words.')
Thanks for any help!

MB
Just look first thread in “Possibly Related Threads...” block (bottom of this page).
I looked in the other threads and didn't find exactly what I was looking for. I found a very similar thread that I think belongs to a classmate, lol. But it's not asking the same questions as me.

I really don't want to rewrite the whole program, I know there is something small that I'm missing and it would work fine.

I'm getting this for output:
Output:
Enter a series of words with spaces in between: monday tuesday wednesday The length of the input is 24 len = 7 monday 0 6 len = 8 tuesday 7 14 len = -15 wednesda 15 -1 There are 3 words.
On the third word, it gets hung up because it's told to find the next space and there isn't one, so right becomes -1. Also, it's not including the last letter of the last word.
How to get it to recognize the end of the word and then stop?

I really do appreciate any help at all.

Thanks!
MB
never mind, I figured it out. :)
Sometimes words are separated by punctuation only (without spaces), e.g. "So,where are Python programmers?". You probably need to handle such cases too...