当我运行以下脚本时
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()如何在这个脚本中起作用?
答案 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()]