2014-03-30 82 views
2

當我運行下面的腳本strip()方法如何與append()方法一起使用?

WORD_URL = http://learncodethehardway.org/words.txt 
WORDS = [] 
for word in urlopen(WORD_URL).readline(): 
    WORDS.append(word.strip()) 
print WORDS 

蟒給出以下輸出:

[ '一個', 'C', 'C', '0', 'U', 'N', ')'

我對strip()方法如何與append()方法一起工作感到困惑?此外readline()如何在這個腳本中起作用?

+0

不要'readline'做'readlines' – sshashank124

+0

@ sshashank124我編輯過那個...... – kartikeykant18

+0

好吧,它現在工作嗎? – sshashank124

回答

2

strip()方法需要你有任何字符串,並刪除尾部空格和換行符

>>> ' asdfadsf '.strip() 
'asdfadsf' 

>>> '\nblablabla\n'.strip() 
'blablabla' 

>>> a = [] 
>>> a.append(' \n asdf \n '.strip()) 
>>> a 
['asdf'] 

>>> words = [' a ', ' b ', '\nc\n'] 
>>> words = [word.strip() for word in words] 
>>> words 
['a', 'b', 'c'] 

更新回答更新問題

from urllib import urlopen 

WORD_URL = 'http://learncodethehardway.org/words.txt' 
WORDS = [] 
word_list = urlopen(WORD_URL) 
word_list = word_list.readlines() 
print word_list      # before strip() 
for word in word_list: 
    WORDS.append(word.strip()) 
print WORDS       # after strip(), so you get an idea of what strip() does 
+0

thnx非常多:) – kartikeykant18

1

str.strip方法實際上應用於word,它是一個字符串。由於strip會刪除word周圍的空格字符,因此會將結果字符串添加到WORDS

您可以使用列表理解(這是比正常循環更有效)這樣

[word.strip() for word in urlopen(WORD_URL).readlines()] 
相關問題