【问题标题】:how does strip() method works with append() method?strip() 方法如何与 append() 方法一起使用?
【发布时间】:2014-03-30 06:41:24
【问题描述】:

当我运行以下脚本时

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() 在这个脚本中的作用是什么?

【问题讨论】:

  • 不要做readlinereadlines
  • @sshashank124 我已经编辑了...
  • 嗯,现在可以了吗?
  • 不,结果相同
  • 执行此操作:将 for 循环更改为 for word in word_list: 并在 for 循环之前添加以下行:word_list = urlopen(WORD_URL).readlines()print word_list。然后告诉我输出。

标签: python list append readline strip


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    str.strip方法实际上是应用在word上,它是一个字符串。由于strip 删除了word 周围的whilespace 字符,因此将生成的字符串添加到WORDS

    您可以像这样使用列表理解(比普通循环更有效)

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

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 1970-01-01
      • 2012-10-24
      • 2013-09-03
      • 2020-09-17
      • 1970-01-01
      • 2016-08-20
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多