替换for循环Python中的字符串元素 [英] Replacing string element in for loop Python

查看:69
本文介绍了替换for循环Python中的字符串元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文本文件中读取数据,所以每一行都是一个字符串列表,所有这些列表都在一个数据列表中.所以我的列表看起来像:

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("%","")

这将正确删除它,但是当我尝试使用嵌套的 for 循环来完成所有操作时:

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!

推荐答案

问题是您的 str 变量遮蔽了内置的 Python str 变量.那个修复很容易.只需使用另一个变量名称.

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

第二个问题是被替换的字符串没有在行列表本身中被替换.修复方法是将替换的字符串保存回 row 列表.为此,您可以使用 enumerate() 为您提供值及其在行中的位置:

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

这篇关于替换for循环Python中的字符串元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆