【问题标题】:Python 2.7 ERROR: 'tuple' object has no attribute 'replace'Python 2.7 错误:“元组”对象没有“替换”属性
【发布时间】:2015-07-14 20:13:40
【问题描述】:

我有一本这样的字典……

 mydict = {"rows": [["col1", "col2", "col3"], ["testing data 1", "testing data 2lk\nIdrjy9dyj", "testing data 3"], ["testing data 2", "testing data 3", "testing data 4"], ["testing data 3", "testing data 4", "testing data 5"]], 
           "columns": ["col1", "col2", "col3"]}

我正在尝试用 html <br> 替换回车符 \n。 这是我得到的错误:

错误:“元组”对象没有“替换”属性

这是我正在尝试使用的代码...如果有人可以提供帮助,我将不胜感激。

for items in mydict['rows']:
            i += 1
            newitems = items.replace("\n", "<br>")
            mydict['rows'][i] = newitems

【问题讨论】:

  • 你的 mydict 包含列表,你的错误提到了元组。其中之一(或代码)一定是错误的。
  • list 也没有 replace 方法。
  • 当然可以,但是这里有更多的奇怪之处(比如i是什么?这不会再出现一个错误吗?),让我们先把问题正确...

标签: python dictionary tuples str-replace


【解决方案1】:

您可以使用以下代码将字符串中的'\n' 替换为'&lt;br&gt;'

for index, sublist in enumerate(mydict['rows']):
    mydict['rows'][index] = [s.replace('\n', '<br>') for s in sublist]

结果

>>> mydict
{'columns': ['col1', 'col2', 'col3'],
 'rows': [['col1', 'col2', 'col3'], ['testing data 1', 'testing data 2lk<br>Idrjy9dyj', 'testing data 3'], ['testing data 2', 'testing data 3', 'testing data 4'], ['testing data 3', 'testing data 4', 'testing data 5']]}

【讨论】:

    【解决方案2】:

    问题是replace 是一个字符串上的方法,你想在每个字符串上调用它,但现在你在集合本身上调用它。你真的想对items 中的每个单独的字符串调用replace,你可以用list comprehension 来做

    for items in mydict['rows']:
                mydict['rows'][i] = [item.replace("\n","<br>") for item in items]
                i += 1
    

    您也可以使用另一个 for 循环而不是列表推导来做到这一点,但是推导很酷,值得了解。

    【讨论】:

      【解决方案3】:

      您可以使用嵌套列表推导进行替换。

      mydict["rows"] = [[item.replace("\n", "<br>") for item in row] 
                         for row in mydict["rows"]]
      
      >>> mydict["rows"]
      [['col1', 'col2', 'col3'],
       ['testing data 1', 'testing data 2lk<br>Idrjy9dyj', 'testing data 3'],
       ['testing data 2', 'testing data 3', 'testing data 4'],
       ['testing data 3', 'testing data 4', 'testing data 5']]
      

      【讨论】:

        【解决方案4】:

        items 是一个元组。

        试试:

        print(type(items))  
        

        因为我得到的脚本错误是:

        AttributeError: 'list' 对象没有属性 'replace'

        并尝试打印items

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-21
          • 1970-01-01
          • 2016-05-17
          • 2014-05-14
          相关资源
          最近更新 更多