python - 替换周围已知但字符串值未知的字符串 Python

标签 python string python-2.7 file-io

我有一个形式的字符串

**var beforeDate = new Date('2015-08-21')**

这里我不知道 paranthesis() 之间的值。我想用任何其他日期替换此日期。我怎样才能在 Python 中做到这一点? 我想打开文件,然后使用该语言的标准替换功能,但由于 () 之间的值未知,所以这是不可能的。

这个片段以及这个片段之后会有很多代码,所以用新行替换整行是行不通的,因为它会覆盖这个片段周围的代码。

最佳答案

使用正则表达式怎么样?示例:

临时文件

print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('2015-08-21') #date determined by fair die roll
print "Here they are, standing in a row"

主要.py

import re

new_value = "'1999-12-31'"
with open("temp.txt") as infile:
    data = infile.read()
    data = re.sub(r"(var beforeDate = new Date\().*?(\))", "\\1"+new_value+"\\2", data)
with open("output.txt", "w") as outfile:
    outfile.write(data)

运行后输出.txt:

print "I've got a lovely bunch of coconuts"
var beforeDate = new Date('1999-12-31') #date determined by fair die roll
print "Here they are, standing in a row"

关于python - 替换周围已知但字符串值未知的字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181489/

相关文章:

c++ - 为科学代码选择前端/解释器

Python:如何编写看起来不错并且可以与 argparse 或 optparse 一起使用的代码?

php - 在列中搜索每个空格分隔值中的字符串

python - python 中 str.find 的最坏情况时间复杂度

python - 带有值检查的生成器表达式

python - Linux允许python使用多少个网口?

python - 使用来自具有相同名称但不同扩展名的不同文件的数据来获取行号

python - 使用 Python 进行基准测试

C - sscanf 可以从它写入的同一个字符串中读取吗?

python - kivy按钮文本=""逻辑错误