我正在创建一个文件,写入其中,然后我想替换一个字符串。我一切都在工作,除了替补。我试过了re.sub公司, 结构更换等等,我想不通。在
target_string = 'foo4bar44foobar444foobar, foo4bar'
file = open(source_file, "w+")
file.write(target_string)
target_string = re.sub('4', '55', target_string)
Desired Output: foo55bar5555foobar555555foobar, foo55bar
谢谢。在
请尝试以下操作,在写入目标字符串之前执行替换并关闭文件:
你所犯错误的官方术语是你的
code
的sequencing
。在在对文件执行}:
re.sub
操作之前,先将target_string
写入文件!您需要切换这些操作,以便write
将修改后的string
改为{另外,当您使用
files
时,理想情况下应该使用with
语句,就像程序在调用file.close()
(我假设您稍后会这样做)之前抛出一个error
语句,您将导致问题。在所以,你最后的
^{pr2}$code
应该看起来像:您需要在写入文件之前更改字符串。在
切换最后两行。在
相关问题 更多 >
编程相关推荐