0

I am trying to break a sentence up into words and then print each word on a separate line. But I am not allowed to use the split function. It should be done using lists and such. So far I have:

text=input("Enter text:")+''
L=len(text)
i=0
while i!=L:
    bi=i
    while text[i]!='':
        i=i+1
        print(text[bi:i])
        i=i+1

But this results in the sentence being broken up letter by letter:

i.e.

"Hello."

becomes:

H
He
Hel
Hell
Hello

Also, what I have now leaves off the last character. And I get the error message:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    while text[i]!='':
IndexError: string index out of range

What does this message mean?

3
  • 2
    while i < L you want the length -1 and while i < L in the inner loop, you should use a for loop checking for whitespace Commented Apr 9, 2016 at 19:05
  • 1
    Are you aware that adding an empty string to another string actually does not change first string (since you are adding literally nothing), right? Similarly, some character taken from string will never be equal to nothing (empty string)/ Commented Apr 9, 2016 at 19:05
  • 1
    For what it's worth, I'm not sure why you're getting downvotes. You've describe your expected and actual results, and included your code. I'm not sure what else other people are expecting from you. Commented Apr 9, 2016 at 19:08

3 Answers 3

2

As I commented your indexing is incorrect, both loops would need to be to the length of the text -1 while i < L, also adding an empty string does not do what you think, text[i] will never be equal to '':

In [1]: text = input("Enter text:") + ''  
Enter text:foo

In [2]: len(text) # still length 3
Out[2]: 3

In [4]: len("")
Out[4]: 0

But a simpler method if your words are delimited by whitespace is to use a for loop, when you encounter whitespace print the chars you have to that point and reset a tmp variable:

text=input("Enter text:")
tmp = ""
for ch in text:
    # if ch is whitespace and we have some chars
    if ch.isspace() and tmp:
        print(tmp)
        tmp = ""
    else:
        tmp += ch
# catch last word
if tmp:
     print(tmp)
Sign up to request clarification or add additional context in comments.

Comments

1

You are getting your error because Python is zero indexed:

test_string = "abc"
print(len(test_string)) # prints 3

foo = test_string[3] # causes error because characters are at indexes 0 - 2
                     # 3 is out of range

You can side step the issue of mismatched indexes by not even using them. Whenever possible, let Python manage the indexes by using a for loop to iterate over a list or string:

s = "this is a string that I want to split"

words = [] # create an empty list of your words
chars = [] # create an empty list of characters

for char in s:

    if char == " " and chars: # if the character is a space and we've stored some chars
        words.append("".join(chars)) # combine the stored chars into a word and add it to 
                                     # the word lise
        chars = [] # clear out the stored chars

    elif char != " ":
        chars.append(char) # otherwise, store the char if it's not a space

if chars:
    words.append("".join(chars)) # add the last word found to the word list

Note that by using the for loop, you don't have to manually manage any indexes.

Comments

-1

You could try regex if using lists is not a hard requirement. This regex breaks a string up into words and returns a list containing the words.

(\S+)\s*

Regex101

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.