python 替换txt中的数字为它的2倍
时间: 2023-02-23 16:36:24 浏览: 35
我可以提供一个简单的Python脚本来实现这一目的,它将把txt文件中的数字替换为它的2倍:with open('file.txt', 'r') as f:
content = f.read()
content = re.sub('\d+', lambda x: str(int(x.group()) * 2), content)with open('file.txt', 'w') as f:
f.write(content)
相关问题
python代码把txt中的数字,替换为指定的内容
可以使用python中的字符串函数replace来替换txt中的数字。例如:txt = 'hello 123 world',可以使用txt.replace('123', 'abc')把txt中的123替换为abc。
python代码 查找并替换txt文件中的数字
可以使用以下Python代码来查找并替换txt文件中的数字:with open('your_file.txt', 'r') as f:
text = f.read()
text = re.sub(r"\d+", 'x', text)with open('your_file.txt', 'w') as f:
f.write(text)