Print each word in string using index slicing

Viewed 4435

I want to print each word in word = "They stumble who run fast" on a new line using index slicing.

I've tried using a while loop, like printing words after each space

word = "They stumble who run fast"
space = word.count(' ')
start = 0
while space != -1:
   print(word[start:space])

The result should be like this:

They
stumble
who
run
fast
5 Answers

If you absolutely need to use index slicing:

word = "They stumble who run fast"

indexes = [i for i, char in enumerate(word) if char == ' ']

for i1, i2 in zip([None] + indexes, indexes + [None]):
    print(word[i1:i2].strip())

Output:

They
stumble
who
run
fast

But why not use .split()?

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

Output:

They
stumble
who
run
fast

I think I know what this problem is for (edx class..as I ran into the same thing). This solution worked for me using the pieces they're encouraging the students to use at this point in the course:

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(" ", space_index+1)
else:
    print (quote[start::1])

The obvious solution would be to use str.split, but that would violate your desire for slicing:

for w in word.split():
    print(w)

A better way might be to keep track of an index for the current space and keep looking for the next one. This is probably similar to what you had in mind, but your loop doesn't update and variables:

start = 0
try:
    while True:
        end = word.index(' ', start)
        print(word[start:end])
        start = end + 1
except ValueError:
    print(word[start:])

A shortcut that probably won't be acceptable either, but produces the desired output:

print(word.replace(' ', '\n'))

Not sure why anyone would want to do this rather than just use str.split(), but here is another (fairly ugly) way along the lines of your initial stab at it.

word = "They stumble who run fast"
while ' ' in word:
    i = word.index(' ')
    print(word[:i])
    word = word[i+1:]
print(word)

# OUTPUT
# They
# stumble
# who
# run
# fast

Posting another way if a student needs an example and must do index slicing.

    check = 0 # Here we start slicing at zero
    
    split = 0
    
    for x in word:
        if x == ' ':  # Will check for spaces
            print(word[check:split])
            check = split + 1  # check will inherit splits value plus one when space found
        split = split + 1  # spit will increase each time no space is found
    print(word[check:split])  # needed to print final word
Related