用python替换字符串

2024-06-13 21:59:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有单子

http://lincoln.com/picture/2453345/flower.jpg
http://lincoln.com/picture/2354345/flower1.jpg

替换为:

http://lincoln.com/picture/4453345/flower.jpg
http://lincoln.com/picture/4354345/flower1.jpg

我试过了:

f=open('fileinput','r')
f.replace('2453345/flower.jpg','4453345/flower.jpg')

但我有更多的台词。我花了很多时间:( 请告诉我如何更换线路。谢谢


Tags: comhttp时间openreplace线路单子jpg
2条回答

我猜当您运行f.replace时会得到AttributeError: 'file' object has no attribute 'replace',因为-well-replace是一个字符串方法,而f是一个file对象。在

替换的一种方法是首先将文件的全部内容读入字符串,然后运行该字符串并将修改后的字符串重写回文件:

f=open('fileinput', 'r')
data=f.read()
f.close()
f.open('fileoutput', 'w')
f.write( data.replace('2453345/flower.jpg','4453345/flower.jpg') )
f.close()

如果您希望每行执行一次替换,只需使用split将数据拆分为多行,然后对其进行迭代:

^{pr2}$

使用正则表达式替换部分字符串

请参阅以下解决方案:

import re
regexp_test = re.compile('\/\d')
result = regexp_test.sub(lambda x: '/'+str(int(x.group()[1])+2), file_content)

它将斜杠(“/”)后的每个数字递增2,因此“/2”将替换为“/4”,以此类推。。。在

结果将为您提供:

^{pr2}$

如果file_content定义如下:

>>> file_content = '''http://lincoln.com/picture/2453345/flower.jpg
http://lincoln.com/picture/2354345/flower1.jpg'''

将文件内容用作字符串

正如@jsalonen正确地注意到的,您的脚本还有另一个问题:它直接使用文件,因为它是一个字符串。你应该先阅读它的内容:

file_content = open('fileinput','r').read()

然后处理file_content变量,它是字符串,包含您所读文件的全部内容。在

相关问题 更多 >