Search code examples
pythonpython-idle

How to find and replace all tabs with spaces in idle


I have an invisible expected an indented block error, which is likely caused by me using tabs instead of spaces.

When I open the "find/replace" window and try to enter TAB in the find field IDLE unsurprisingly just skips to the replace field.

How do I do this?


Final update:

Thank you for all answers, much appreciated. My problem was that python wants the function comments to be indented too, that is

def imdheladumb():
"""
I'm dum as hel
"""

does not work, it needs to be

def imdheladumb():
    """
    I'm dum as hel
    """

Solution

  • IDLE doesn't let you search to literal tab characters. You can paste one into the search box (as suggested by will), but it will never match anything.

    However, it does let you do regular expression searches, and the regular expression \t will match a literal tab. So, turn on the Regular expression checkbox, and put '\t in the Find: box, and 4 or 8 spaces (as appropriate) in the Replace: box.

    But, as will suggested, it's better to use IDLE's features instead of trying to do things manually: Select the block of code with tabbed (or inconsistent) indentation, go to the Format menu, and select Untabify Region. (Or just hit control-6.) If the tabs were inserted with an editor that uses 4-space tabs, you may need to first use New Indent Width and change it to 4, then Untabify Region.

    IDLE doesn't have any code to guess what your tab size was when you wrote the inconsistent code. The only editor I know of that does is emacs. If you just open the file in emacs, it will try to guess your settings, and then you can select the whole buffer and untabify-region. If it guessed right, you're golden; if it guessed wrong, don't save the buffer, because now it'll be even harder to fix. (If you're one of the 3 people in the world who knows how to read emacs lisp but doesn't like emacs, you could look through the python-mode.el source and see how it does its magic.)