strip()方法如何与append()方法一起使用?

时间:2014-03-30 06:41:24

标签: python list append readline strip

当我运行以下脚本时

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

python提供以下输出:

[' a',' c',' c',' o',' u',& #39; n',' t','']

我对strip()方法如何使用append()方法感到困惑?另外readline()如何在这个脚本中起作用?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

str.strip方法实际应用于word,这是一个字符串。当strip删除word周围的whilespace字符时,结果字符串会添加到WORDS

您可以使用List Comprehension(比正常循环更有效),如此

[word.strip() for word in urlopen(WORD_URL).readlines()]