Skip to main content
 首页 » 编程设计

python之是否可以搜索并替换为 "any"个字符的字符串

2025年05月04日40lovecherry

可能有几种方法可以解决这个问题,所以我愿意接受任何想法。

我有一个文件,该文件中有字符串“D133330593”注意:我确实知道该字符串在文件中的确切位置,但我不知道这是否有帮助。

这个字符串后面有6位数字,我需要用另外6位数字替换这6位数字。

这是我目前所拥有的:

def editfile(): 
    f = open(filein,'r') 
    filedata = f.read() 
    f.close() 
 
    #This is the line that needs help 
 
    newdata = filedata.replace( -TOREPLACE- ,-REPLACER-) 
 
    #Basically what I need is something that lets me say "D133330593******"  
    #->"D133330593123456" Note: The following 6 digits don't need to be  
    #anything specific, just different from the original 6 
 
    f = open(filein,'w') 
    f.write(newdata) 
    f.close() 

请您参考如下方法:

使用 re 模块定义您的模式,然后使用 sub() 函数用您自己的字符串替换该模式的出现。

import re 
 
... 
 
pat = re.compile(r"D133330593\d{6}") 
re.sub(pat, "D133330593abcdef", filedata) 

上面将模式定义为 -- 您的字符串 ("D133330593") 后跟六位十进制数字。然后下一行用您的替换字符串(在本例中为“abcdef”)替换所有出现的此模式,如果这是您想要的。

如果您想为每次出现的模式使用一个唯一的替换字符串,那么您可以在 sub() 函数中使用 count 关键字参数,它允许您指定必须进行更换的次数。

查看此库以获取更多信息 - https://docs.python.org/3.6/library/re.html