[問題] split syntax

看板Python作者 (獨在異鄉為異客)時間17年前 (2008/02/20 11:48), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/2 (看更多)
I'm writing a python script about "split" function, trying to use space to split a string. It should work the same way as the built-in split function. For example, "This is a sentence" should have the output ['This', 'is', 'a', 'sentence'] This the is script I have so far, but it won't give me the last word in the sentence. If anyone knows how to fix it, I'll appreciate it very much. >>> word = "" >>> output = [] >>> input = "This is a sentence" >>> for x in input: ... if x not in " ": ... word = word + x ... else: ... output.append(word) ... word = " " ... >>> output ['This', ' is', ' a'] I guess it's because there's only three space between the words so I get this output, but this the the closest I can get. I have to admit that this is my homework, but I've been working on it for three days. I hope I can get some feedback on it. By the way, I just had one lesson on python. I don't know many of the commands yet (as you can see from this simple script). I'd appreciate it if you can use simple language to fix this script. Sorry I have to type in English. I have no access to Chinese now. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 69.143.181.102

02/20 13:02, , 1F
input.split()
02/20 13:02, 1F

02/20 13:08, , 2F
we can't use the built-in function
02/20 13:08, 2F

02/20 13:09, , 3F
that's why I have to write the command
02/20 13:09, 3F
文章代碼(AID): #17kwCYBp (Python)
討論串 (同標題文章)
以下文章回應了本文
完整討論串 (本文為第 1 之 2 篇):
1
3
文章代碼(AID): #17kwCYBp (Python)