如何使用regex-python替换特定部分

2024-09-30 14:16:39 发布

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

视图.py

combineKeyword =""myKeyword", "Auto", "st3-throttling-cdb", "functional""
template_desc2 = "@Test(groups = { "Code-planned", "Code-not automated", "Code-st3reporter" }
import re
re.sub(r' @Test\(groups\s*=\s*\{([^\}]+)',combineKeyword,template_desc2)

这里我想替换“Code planned”、“Code not automated”、“Code-st3reporter”这些关键字,并将combineKeyword放在那里


Tags: pytestre视图autonotcodetemplate
1条回答
网友
1楼 · 发布于 2024-09-30 14:16:39

您的示例有语法错误,我假设字符串被包装在单引号中'',而内部字符串类似于"Code-planned"

s = '@Test(groups = { "Code-planned", "Code-not automated", "Code-st3reporter" ,"different"}'

print  re.sub('Code-[^"]*',"my new string",s )

@Test(groups = { "my new string", "my new string", "my new string" ,"different"}

如果要替换所有字符串(无论是否以代码开头):

s = '@Test(groups = { "Code-planned", "Code-not automated", "Code-st3reporter" ,"different"}'

print re.sub(r'\"(.*?)\"','"my new string"',s)

@Test(groups = { "my new string", "my new string", "my new string" ,"my new string"}

相关问题 更多 >

    热门问题