Re: [問題] split syntax

看板Python作者 (生の直感、死の予感)時間17年前 (2008/02/20 14:56), 編輯推噓1(106)
留言7則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《azulazure (獨在異鄉為異客)》之銘言: : 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. : ... if x not in " ": : ... word = word + x : ... else: : ... output.append(word) : ... word = " " : ... : ['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. inpu = "This is a sentence" word = "" output = [] for x in inpu: if x not in " ": word = word + x else: output.append(word) word = " " output.append(word) ^^^^^^^^^^^^^^^^^^^^^^^^^^ <-- you JUST need add this line or you can try this : inpu = "This is a sentence" word = "" output = [] for x in inpu + ' ': <-- add a space in the end of input sentence if x not in " ": word = word + x else: output.append(word) word = " " -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.110.216.36

02/20 21:04, , 1F
thank you so much..the first one doesn't work on my
02/20 21:04, 1F

02/20 21:04, , 2F
machine, but the second one works great!
02/20 21:04, 2F

02/20 21:05, , 3F
and the 2nd one makes a lot of sense to me
02/20 21:05, 3F

02/20 21:06, , 4F
one more question, does it make any difference if
02/20 21:06, 4F

02/20 21:06, , 5F
I use single quote or double quote for the added
02/20 21:06, 5F

02/20 21:07, , 6F
space? (' ' and " ") cause " " failed but ' ' works
02/20 21:07, 6F

02/20 22:44, , 7F
i think ' ' and " " are the same. i am using python2.5
02/20 22:44, 7F
文章代碼(AID): #17kyyTXm (Python)
討論串 (同標題文章)
本文引述了以下文章的的內容:
1
3
完整討論串 (本文為第 2 之 2 篇):
1
3
文章代碼(AID): #17kyyTXm (Python)