【问题标题】:Unable to perform string operations on the list elements [closed]无法对列表元素执行字符串操作 [关闭]
【发布时间】:2021-08-05 17:55:15
【问题描述】:

我有一个清单,

list1 = [<td>-267</td>, <td>1,420</td>, <td>1,997</td>, <td>1,241</td>]

我想从里面的项目中删除 &lt;td&gt;&lt;/td&gt; ,所以我这样做了:

# Created empty list:
final = []

# then,
for i in list1:
    i.replace('<td>', '').replace('</td>', '')
    final.append(i)

给出错误 TypeError: 'NoneType' object is not callable while appending to empty list。

这里很好用:

a = '<td>-267</td>'
a.replace('<td>', '').replace('</td>', '')

输出 = '-267'

为什么它不适用于 append 方法?

【问题讨论】:

  • 您缺少赋值语句,i = i.replace('&lt;td&gt;', '').replace('&lt;/td&gt;', '') 然后追加或只是 final.append(i.replace('&lt;td&gt;', '').replace('&lt;/td&gt;', ''))
  • 这看起来像 XY 问题。您是如何首先获得列表的?看起来您尝试解析 html 源代码,所以请使用 BeautifulSoup。

标签: python string list for-loop append


【解决方案1】:

你做的几乎是对的,只是你错过了给 i 赋值

Created empty list:
final = []
then,
for i in list1:
    i=i.replace('<td>', '').replace('</td>', '')
    final.append(i)

【讨论】:

    【解决方案2】:
    list1 = ['<td>-267</td>', '<td>1,420</td>', '<td>1,997</td>', '<td>1,241</td>']
    final = []
    
    for i in list1:
        i = i.replace('<td>', '').replace('</td>', '')
        final.append(i)
    print(final)
    

    首先你的列表应该是字符串值,然后试试上面的代码

    【讨论】:

      【解决方案3】:

      在替换

      和 之后,您必须将其分配回变量“i”:
      final1 = []
      for i in ["<td>-267</td>", "<td>1,420</td>", "<td>1,997</td>", "<td>1,241</td>"]:
          i = i.replace("<td>", "").replace("</td>", "")
          final1.append(i)
      print(final1)
      

      输出:['-267', '1,420', '1,997', '1,241']

      【讨论】:

        【解决方案4】:

        您没有将值分配回i字符串 是不可变的数据类型,因此replace 方法返回 一个字符串的副本,其中所有出现的子字符串都被另一个子字符串替换。

        list1 = ["<td>-267</td>", " <td>1,420</td>", " <td>1,997</td>", " <td>1,241</td>"]
        
        final = []
        for i in list1:
            i = i.replace('<td>', '').replace('</td>', '')
            final.append(i)
        print(final)
        

        【讨论】:

          猜你喜欢
          • 2011-10-30
          • 2016-08-03
          • 2016-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多