Problems re-appending spaces to a string in python

Question:

I have a problem where I’m trying to take the text string string "The quick brown fox jumps over the extraordinarily lazy dog" and convert it into an array of characters whilst also storing an array of integers where the integer represents the end of a word. I managed to do this by using a char space = ‘ ‘ and checking if the char is a space or not.

Now, I have a successful array of characters and integers which are correct to the last letter of each word, but when I try to put them together to output the same string as the input, my code adds spaces in the wrong section and I have no idea why.

import enum

#string
string = "The quick brown fox jumps over the extraordinarily lazy dog"

#supposed to be the same as string
output_string = ""

#array to hold char of string without spaces
text = []
#array to hold indexes of ends of words
end = []
#space char to check for word end
space = ' '

#for while
x = 0

#loops through each character in the string
#if it detects a space it adds that index to an array
for i, string in enumerate(string):
    print(i, string)
    if string == space:
        end.append(i - 1)
    if string not in space:
        text.append(string)

#while there's still text in the array
while x < len(text):
    #checks if x is in the array of word end indexes
    if x in end:
        #adds letter 
        output_string += text[x]

        #adds space
        output_string += " "

    #otherwise just add letter
    else:
        output_string += text[x]
    
    #increment the count
    x = x + 1

#print the output string
print(output_string)

At the moment this is my output:

The quickb rownfo xjum psover theex trao rdinarilylazydog

I’m sure it has to do with the fact that the array size with spaces is larger than without but I don’t know how to correct this.

For those of you wondering, I’m learning data structures and algorithms at University and thought I’d try implement a string pool in python

Asked By: Damon O'Neil

||

Answers:

Since you choose to use a while loop to merge the end and text correctly, I would recommend you to use another iterating variable along with x (as per your code). Say the variable is y=0.
We’ll use x to look for spaces and y to look for text.

# All the code remains unchanged
y = 0

while y < len(text):

    #checks if x is in the array of word end indexes
    if x in end:
        #adds space
        output_string += " "
        
    #otherwise just add letter
    else:
        output_string += text[y]
        y += 1

    #increment the count
    x = x + 1

Edit: I forgot to mention, you need to use the iterator variable y to check the condition since y will be used to pull out the text using it as the index value.

Answered By: Emmanuel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.