用字符串代替整数的区间

2024-04-25 08:51:49 发布

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

我想用数据中的字符串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之间?你知道吗


Tags: 数据字符串testreis整数thiscontrol
2条回答

如果字符串那么简单,您可能需要考虑拆分它们、解析int、比较和替换。你知道吗

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

使用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

相关问题 更多 >