Replacing string element in for loop Python

后端 未结 3 707
轻奢々
轻奢々 2021-01-27 21:44

I am reading data in from a text file so each row is a list of strings, and all those lists are in a data list. So my lists look like:

data = [row1, row2, etc.]
         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 22:14

    The problem is that your str variable is shadowing the builtin Python str variable. That fix is easy. Just use another variable name.

    The second problem is that the replaced string isn't being replaced in the row list itself. The fix is to save the replaced string back into the row list. For that, you can use enumerate() to give you both the value and its position in the row:

    for row in data:
        for i, x in enumerate(row):
            x = x.replace("%","")
            x = x.replace("$","")
            row[i] = x
    

提交回复
热议问题