当我运行以下脚本时
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','n','t','']
我对strip()方法和append()方法如何工作感到困惑?还有readline()在此脚本中的作用?
最佳答案
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
关于python - strip()方法如何与append()方法一起使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22741088/