sub()缺少1个必需的位置参数:“string”

2024-06-26 00:05:38 发布

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

我写了这样一个正则表达式重复冗长在

#+begin_src ipython :session flask :results output
import re

def clearup(path):
    fp = open(path, 'r+')
    text = fp.read()
    text = re.sub(r'''.*PROPERTIES:.*\n
                      (?:.*\n)* # multiple lines in the middle
                      .*:END: ''',text, flags=re.VERBOSE)
    fp.seek(0)
    fp.write(text)
    fp.close()

clearup("01.foreword.org")
#+end_src

运行但报告错误:

^{pr2}$

有什么问题,因为没有遗漏论点?在


Tags: pathtextimportresrcflaskoutputsession
2条回答

sub接受三个变量(不包括标志)。第一种是regex模式。第二种是替代regex。第三个是要从中派生的字符串。我认为这就是你得到的错误,因为你似乎没有替代模式,只有文本。在

来自python文档:https://docs.python.org/3/library/re.html#re.sub

re.sub(pattern, repl, string, count=0, flags=0)

很多争论重复冗长,这是如此令人困惑,而且参数的位置很容易出错。在

所以我建议将定义模式和.sub移动分成两行:

^{pr2}$

在我看来这更具可读性。在

相关问题 更多 >