Search code examples
pythonpycharmsublimetextdocstring

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


I have a long source code in python, and many functions are documented with '''xxx''', How do I replace them with """xxx""" quickly? in any text editor ? pycharm / sublime

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

desired result:

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

edit: Found the solution in pycharm ( or every other text editor) search for '''(\n.*\n\s*)'''\n and replace with """$1"""\n

ps: I can not just do a simple search for ''',and replace it with """, because in the code multi line strings are everywhere, not just in the docstring.


Solution

  • You can achieve it by three methods,

    Method 1: Inspect whole project

    Go to Code > Inspect Code. PyCharm will scan your code (this may take some time) and will show you the inspection results.

    In the inspection results, under Python It will show Single Quoted docstrings enter image description here

    1. To change all the files at once
      Select Single quoted docstring from the left pane and click Convert docstring to the triple double quoted string form. Now all the files will be changed to triple double quotes.

    2. To change for individual files
      Select individual files under Single quoted docstring and for each file click Convert docstring to the triple double quoted string form.

    Method 2: Replace Code with Replace in Path

    In PyCharm, right click on the project and select Replace in Path or Ctrl+Shift+R. enter image description here enter image description here

    In the Text to find field, enter ''' and in Replace with field, enter """. click find. PyCharm will scan through the files and ask you whether to replace single occurrence, or all occurences at once.

    Method 3: Use terminal tools or Python to read lines and replace.

    As others mentioned, this method will do the job.

    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.