使用regex替换后面的值=

2024-03-28 09:17:04 发布

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

我有一个字符串如下所示

abcdefg=12345
abcdefg=551234
abcdefg=111323
abcdefg=567454

我想用一个正则表达式来替换它,这样值就变成

abcdefg=456789

我用下面的代码来做

str1=string.split('=')
line=str1[0]+'='+"456789"

有没有更好的方法使用正则表达式


Tags: 方法字符串代码stringlinesplitstr1abcdefg
2条回答

试着这样做:

text = 'abcdefg=12345'
head, sep, tail = text.partition('=') + "=456789"

>>> print head
abcdefg=456789

从文档中:

partition(...) S.partition(sep) -> (head, sep, tail)

Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings.

  import re
  x="abcdefg=12345"
  print re.sub(r"(.*?)=\d+",r"\1=456789",x)

使用纯稀土。你知道吗

相关问题 更多 >