python替换bat文件中的子字符串

2024-04-30 04:01:08 发布

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

我有一个bat文件,需要在其中替换中的子字符串。我要替换的文本包含在以下字符串中:

this line has alot of text sim-manager-ui-38.05.00.00-THISHOT-other-stuff

我要替换的部分是38.05.00.00,因为它将根据用户请求使用不同的值。此号码将由用户提供。然后,我还想在数字被替换后删除'THISHOT'部分

如何替换数值和删除“THISHOT”部分?例如,如果我想要数字40.00.00.00,我希望该行的内容如下:

this line has alot of text sim-manager-ui-40.00.00.00-other-stuff

Tags: of字符串text用户uilinemanager数字
1条回答
网友
1楼 · 发布于 2024-04-30 04:01:08

可以使用正则表达式查找并替换该零件

import re
import random

def pattern():
    return ".".join( str(x) for x in( random.randint(10,99) for i in range(4)) )

s = "this line has alot of text sim-manager-ui-38.05.00.00-THISHOT-other-stuff"

# If you want to only remove -THISHOT part you can: 
print(s.replace("-THISHOT", ""))

# If you want to replace that number pattern with another random number:
output = re.sub("(\d\d.*)*-THISHOT", pattern(), s)
print(output)
# this line has alot of text sim-manager-ui-12.56.81.14-other-stuff

相关问题 更多 >