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

标签 python regex

我有一个文件看起来像

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")])

关于python - 如何使用 Python 替换本文中的冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16309524/

相关文章:

objective-c - Objective-C/iOS : Look through a document for any one of several thousand words?

python - 导入错误 : No module named opencv after installing python-opencv

python - 使用 South AND django 1.7 迁移的可重用应用程序的升级路径

python - 如何使用正则表达式在 python 字符串中找到 str.format 的所有占位符?

c# - 正则表达式用匹配索引替换字符

regex - htaccess - Rewriterule 重定向到错误的 URL

java - 正则表达式匹配被双引号引用的单引号

Python函数调用

python - 如何将我的函数导入到 python 文件并从中获取输入?

python - 哪个 Python IDE 具有 Visual Studio 功能?