用字符串替换整数区间



我想用数据中test的字符串替换 100 到 200 之间的所有整数。以下是一些控制案例:

`this is a control 150` = `this is a control test`
`this is a control 160` = `this is a control test`
`this is a control 150000` = `this is a control 150000`

我的想法是使用正则表达式,我有以下内容:re.sub("d", "test", "this is a control 150")

但是,这会将所有整数替换为test。有没有办法将其限制为仅替换 100-200?

使用re.search

演示:

import re
s = ["this is a control 150", "this is a control 160", "this is a control 160.05", "this is a control 150000"]
for i in s:
m = re.search("d+.?d*", i)
if m:
if 100 < float(m.group()) < 200:
print(i.replace(m.group(0), "test"))
else:
print(i)

输出:

this is a control test
this is a control test
this is a control test
this is a control 150000

如果你的字符串这么简单,你可能要考虑拆分它们,解析一个整数,比较和替换。

for line in your_lines:
num = int(line.split("control ")[1])
if num > 100 and num < 200:
line.replace(str(num), 'test')

最新更新