0

Could you tell me what's wrong here?

For some reason there's nothing added into the list.

textarea = raw_input()
n=0
txa = []
string =""

while(n < len(textarea)):
    if(textarea[n] != ' ' or textarea[n] != ','):

        string += textarea[n]
        n=n+1
        print (string)

    else:
        print "For some reason I'm never here."

        if(string == ' ' or string == ','):
            string = ""
        else:
            txa.append(string)
            string = ""
            n=n+1
print(txa)

Sorry for my english.

Sharki
  • 404
  • 4
  • 23

3 Answers3

0

You need to change the or in your if statement to an and. Currently the condition is always true because it is impossible for textarea[n] to be both ' ' and ','.

You can also use regular expressions to split the string as seen here

jonbush
  • 56
  • 4
0
>>> txt = "Hello, goodbye Fred"
>>> txt.replace(',', ' ').split()
['Hello', 'goodbye', 'Fred']
ShpielMeister
  • 1,417
  • 10
  • 23
  • Hey, I was trying with your code, I'm sure it works perfectly, but I'm a bit idiot, so I couldn't get it to work. Anyway, I solved with: `"textarea.split(", ")"` Thank you! – Sharki Dec 07 '17 at 07:20
0

First, you need to change or in your 1st if with and.

Second, if-else block in the 1st else is redundant. Try deleting it, but retaining the code in the 2nd else block.

Third, add an append just after the while so that the last word that is stored in the string variable also gets into the txa list.

Your code will pretty much, look like this -

while(n < len(textarea)):
    if(textarea[n] != ' ' and textarea[n] != ','):
        string += textarea[n]
        n=n+1
        print (string)

    else:
        print ("For some reason I'm never here.")
        txa.append(string)
        string = ""
        n=n+1

txa.append(string)
print(txa)

Tip: Moreover, you can try using in-built functions to do splitting for you.

txa = str(raw_input()).replace(',', ' ').split()

This one-liner works just fine.