如何使用三重双引号而不是三重单引号制作所有文档字符串?

How do I make all the docstring using triple double quotes instead of triple single quotes?

我在python里面有很长的源码,很多函数都是用'''xxx'''说明的,如何快速替换成"""xxx"""?在任何文本编辑器中? pycharm/崇高

def my_func():
    '''
    yeah a doc string
    '''
    pass

期望的结果:

def my_func():
    """
    yeah a doc string
    """
    pass

编辑: 在 pycharm(或所有其他文本编辑器)中找到解决方案 搜索 '''(\n.*\n\s*)'''\n 并替换为 """"""\n

ps:我不能简单地搜索''',然后用"""替换它,因为在代码中多行字符串无处不在,而不仅仅是在文档字符串。

生效:

:%s/'''/"""/g *<return>*
python -c "import sys;with open(sys.argv[1],'rb') as f: tmp = f.read();with open(sys.argv[1],'wb') as f:f.write(tmp.replace(\"'''\",'\"\"\"')"

将我的评论变成答案。如果你有很多文件,正则表达式是你的朋友。从 GNU/Linux 终端,你可以写:

find path/to/dir -name '*.py' -exec perl -p -i -e \'s/'''/"""/g\' {} \;

可以通过三种方式实现,

方法一:检查整个项目

前往 Code > Inspect Code。 PyCharm 将扫描您的代码(这可能需要一些时间)并显示检查结果。

检查结果中,Python下会显示Single Quoted docstrings

  1. 一次更改所有文件
    Select Single quoted docstring,然后单击 Convert docstring to the triple double quoted string form。现在所有文件都将更改为三重双引号。

  2. 为单个文件更改
    Select Single quoted docstring 下的单个文件并为每个文件单击 Convert docstring to the triple double quoted string form

方法二:用Replace in Path

替换代码

在PyCharm中右击项目然后selectReplace in PathCtrl +Shift+R

Text to find 字段中输入 ''',在 Replace with 字段中输入 """。点击查找。 PyCharm 将扫描文件并询问您是替换单个事件还是一次替换所有事件。

方法 3:使用终端工具或 Python 读取行并替换。

正如其他人提到的,此方法可以完成工作。

I recommend method 1 Since PyCharm is intelligent, it can change doctrings without changing multi-line strings (if you are using it) which is prone to replacement in other methods.