Python 使用.Replace()将一个字符串变量替换为更宽字符串变量中的另一个字符串变量
我有一些数据如下所示:Python 使用.Replace()将一个字符串变量替换为更宽字符串变量中的另一个字符串变量,python,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,31
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
我有一些代码使用反向拆分从右边取第五个元素(在顶行中,这是'33333'),并用逗号拆分,得到'3,3,3,3'
执行此操作的代码是(其中“match3g”解析为上面打印的字符串):
因此,这里再次使用数据顶行的示例,'spl'解析为'33333','spl2'解析为'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()方法时,它并没有按照需要将“spl1”替换为“spl2”
我认为这不会有任何问题,因为“match3g”、“spl1”和“spl2”现在都是字符串
谁能告诉我我做错了什么
感谢在for循环中,
行
是一个变量,它引用由match3g.split(“\n”)
生成的列表的当前迭代中的字符串。分配给该变量没有多大意义
我假设您希望更新“parent”字符串match3g。您不能通过指定行
变量来完成此操作
您可以尝试创建一个新字符串,称之为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\u match3g
,它包含您想要的所有替换项
希望这有帮助。您是否希望
replace()
替换文件中的行?在这种情况下,您可能需要查看fileinput
模块-@shaktiman hi,谢谢您的回复。是的,确实如此,因此字符串“match3g”中的子字符串“33333”将变为“3,3,3,3”。谢谢。您的代码中没有任何内容正在修改match3g
。
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'