Replacing string element in for loop Python

孤人 提交于 2021-02-05 12:13:40

问题


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.]
row1 = [str1, str2, etc.]

I am trying to remove any $ or % signs that appear in the strings in a row list. I have checked that if I try and do this for one individual element, say the second row and the fourth element has a "%", so:

data[1][3] = data[1][3].replace("%","")

This will properly remove it, but when I try and use a nested for loop to do it all:

for row in data:
    for x in row:
        x = x.replace("%","")
        x = x.replace("$","")

This doesn't remove any of the % or $ signs, I have tried just doing it without the second replace to see if it would at least remove the % signs, but even that didn't work.

Any ideas why this wouldn't work, or how I could do this?
Thanks in advance for any help!


回答1:


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



回答2:


You are assigning a new value to the name x but that does not change the contents of row or data. After changing x, you need to assign row[j] = x or data[i][j] = x for the appropriate column index j (and row index i). See also python 3: lists dont change their values




回答3:


Also in your in this case you can use list comprehension

data = [[item.replace("%", "").replace("$", "0") for item in row] for row in data]


来源:https://stackoverflow.com/questions/39682342/replacing-string-element-in-for-loop-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!