Skip to main content
 首页 » 编程设计

python之如何使用 Python 替换本文中的冒号

2025年05月04日10linjiqin

我有一个文件看起来像

1::12::33::1555 
1::412::1245::23444 

等等。我需要去掉最后一个参数,并将冒号替换为逗号。我试过:

  myfile = open('words.txt', 'r') 
  content = myfile.read() 
  content = re.sub(r'(.+)::(.+)::(.+)::(.+)', "\1,\2,\3", content) 
  myfile = open('words.txt', 'w') 
  myfile.write(content)    
  # Close the file 
  myfile.close() 

但是后向引用不起作用,我最终得到了一个带逗号的文件..

我希望实现的是:

1,12,33 
1,412,1245 

请您参考如下方法:

反向引用只会插入原始字符串。

re.sub(r'(.+)::(.+)::(.+)::(.+)', r"\1,\2,\3", content) 

你也可以使用纯字符串/列表来做到这一点

"\n".join([",".join(y.split('::')[:-1]) for y in content.split("\n")])