Sociopath
Sociopath

Reputation: 13426

Change indentation of python script in Spyder

I have a very long python script. I want to make some changes in it. But it uses 2 spaces indentation while I want to use TAB or 4 spaces indentation.

I know how to change Indentations while writing a script.

Tools >>> Preferences >>> Editor >>> Advanced settings >>> Indentation characters

But it's not working with existing scripts.

So how can I change the indentations to 4 spaces or TAB in my file?

PS: For now I don't have other editors to work with. So I am stuck with spyder only.(and Notepad++)

Upvotes: 0

Views: 1113

Answers (1)

GPhilo
GPhilo

Reputation: 19143

Solution 1)

As suggested in the comment, just find-and-replace " " (2 spaces) with " " (4 spaces). This might replace double-spaces inside your code as well, but it's the simplest and quickest solution. Beware of hardcoded strings with double spaces, those will break.

Solution 2)

Regexes! In a different script (or the console), run:

import re
with open('my_script_with_2_spaces.py') as fp:
  text = fp.read()

def gen_replacement_string(match):
  print(match)
  print(match.groups())
  return '    '*(len(match.groups()[0])//2)

with open('my_script_with_4_spaces.py', 'w') as fp:
  fp.write(re.sub(r'^((?:  )+)', gen_replacement_string, text, flags=re.MULTILINE))

What does the regex do?

  • ^ matches the beginning of the line (requires the MULTILINE flag)
  • the outer (...) is needed to consider ... (its content) as one group, so I can then retrieve it easily (it's the match.groups()[0] in gen_replacement_string)
  • the inner (?: )+ is a non-capturing group repated one-or-more times that matches two spaces

So, all in all I'll match all spaces-only strings with multiple-of-two length that appear at the beginning of a line. That's the indentation we want.

re.sub takes as a second parameter a function that I use to generate dynamically the replacement string, since we want it to have the same indentation depth as the original. This happens in gen_replacement_string.

Upvotes: 2

Related Questions