-3

Each word needs to be on a different line in a given statement and am not able to print the last word.

# [ ] Print each word in the quote on a new line  
quote = "they stumble who run fast"
start = 0
space_index = quote.find(" ")
while space_index != -1:
    print(quote[start:space_index])
    start = space_index+1
    space_index = quote.find(" ",start)
    if space_index == -1:
        print(space_index[start:])
Expected output:
they
stumble
who
run
fast

I am not able to print the last word: "fast"

Coder_G
  • 5
  • 1
  • 3
  • 1
    The error: `print(space_index[start:])`. Sure you know that `space_index` is a number. – 9000 Jun 03 '19 at 16:05
  • You people are so quick. I just found it myself, yet within minutes I received four answers. – Coder_G Jun 03 '19 at 16:11
  • `print(*quote.split(), sep='\n')` does this for you, unless you are trying to make your own version for practice. – N Chauhan Jun 03 '19 at 16:12
  • @Coder_G - That would suggest you didn't research your own issue much before posting – Sayse Jun 03 '19 at 16:19
  • Possible duplicate of [what does 'int' object is not subscriptable mean?](https://stackoverflow.com/questions/33647685/what-does-int-object-is-not-subscriptable-mean) – Sayse Jun 03 '19 at 16:24

4 Answers4

1

I think you meant print(quote[start:]). And there are much simpler ways to do this.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Change your last code as below. Most probably it is a typo error.

if space_index == -1: 
    print(space_index[start:])

to:

if space_index == -1: 
    print(quote[start:])
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
0

The mistake is space_index is an int and you intended to do print(quote[start:]) instead.

Alternatively, you might like to do the following

quote = "they stumble who run fast"
quote = quote.split()
for i in quote:
    print(i)
Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
0

space_index is an integer so you cannot do:

print(space_index[start:])

This is because for the same reason you cannot do, for example, 2[3:].

You need to use:

print(quote[start:])

A better approach for this problem is just:

quote = "they stumble who run fast"
print(*quote.split(), sep='\n')

which prints:

they
stumble
who
run
fast
Austin
  • 25,759
  • 4
  • 25
  • 48