使用.replace()将一个字符串变量替换为更宽的字符串变量中的另一个

时间:2014-08-25 16:48:32

标签: python

我有一些看起来像这样的数据:

10272,201,Halifax,1,33333,1,333,3,33
,10272,206,Barnet,2,33033,5,303,2,33
,10272,989,Forest Green,3,33311,4,331,11,31
,10272,6106,Eastleigh,4,33103,3,313,12,30
,10272,203,Lincoln,5,13330,11,13,5,330
,10272,921,Gateshead,6,33103,18,30,1,313
,10272,199,Wrexham,7,30331,14,031,4,33
,10272,164,Grimsby,8,11133,7,113,7,13
,10272,991,Woking,9,31113,8,113,8,31
,10272,749,Kidderminster,10,13311,2,331,13,11
,10272,205,Macclesfield,11,33111,12,31,6,311
,10272,1392,Aldershot,12,30311,10,31,10,031
,10272,3551,Braintree Town,13,03003,6,303,21,00
,10272,204,Torquay,14,03111,9,311,16,01
,10272,919,Southport,15,00131,16,03,14,011
,10272,185,Bristol Rovers,16,10031,13,13,17,001
,10272,213,Chester,17,00301,24,00,9,031
,10272,909,Dover,18,00130,15,03,20,010
,10272,1389,Altrincham,19,00300,17,030,22,00
,10272,982,Telford,20,10001,21,001,15,10
,10272,6140,Dartford,21,01010,20,01,19,100
,10272,1395,Welling,22,10010,19,11,23,000
,10272,913,Nuneaton,23,01000,23,00,18,100
,10272,2792,Alfreton,24,00000,22,00,24,000

我有一些代码使用反向拆分从右边获取第5个元素(在顶行中这是'33333')并用逗号分隔它以给出'3,3,3,3,3'。

执行此操作的代码是(其中'match3g'解析为上面打印的字符串):

for line in match3g.split("\n"):
                spl = line.rsplit(",",5)[-5:-4]
                if spl:
                    spl2 = "{}".format(",".join(list(spl[0])))

所以这里再次使用顶行数据的例子,'spl'解析为'33333','spl2'解析为'3,3,3,3,3'。我当时想做的是在更宽的字符串'match3g'中用'spl2'替换'spl'。我试图通过添加到上面的'for'循环来实现这一点,现在它读作:

for line in match3g.split("\n"):
            spl = line.rsplit(",",5)[-5:-4]
            if spl:
                spl1 = "{}".format("".join(list(spl[0])))
                spl2 = "{}".format(",".join(list(spl[0])))
                spl2 = str(spl2)
                spl1 = str(spl1)
                line = line.replace(spl1, spl2)

我已将新字符串变量'spl1'和'spl2'的值打印到屏幕以确认它们是我期望的格式(它们是什么),但是当我尝试使用.replace()方法时它不是根据需要用'spl2'代替'spl1'。

我认为这没有问题,因为'match3g','spl1'和'spl2'现在都是字符串。

谁能告诉我我做错了什么?

由于

1 个答案:

答案 0 :(得分:1)

在for循环中,line是一个变量,它引用match3g.split("\n")生成的列表的当前迭代中的字符串。分配给该变量没有多大意义。

我假设您希望更新'parent'字符串match3g。您无法通过分配line变量来执行此操作。

您可能会尝试创建一个新字符串,将其命名为new_match3g,并在for循环的每次迭代期间附加到该字符串:

new_match3g = ''
for line in match3g.split("\n"):
        spl = line.rsplit(",",5)[-5:-4]
        if spl:
            spl1 = "{}".format("".join(list(spl[0])))
            spl2 = "{}".format(",".join(list(spl[0])))
            spl2 = str(spl2)
            spl1 = str(spl1)
            new_match3g += line.replace(spl1, spl2) + '\n'

然后在for循环结束时,您将拥有一个变量new_match3g,其中包含您想要的所有替换项。

希望这有帮助。

相关问题