How to find and replace all tabs with spaces in idle - python

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
"""

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.)

A generic way to do this is to just copy a tab character from the document (or just do one in any random text editor and copy it) and then put that into the field.
You could try putting \t in there, but that only works in some editors.
Most IDEs have a function to automatically replace tabs with a predefined number of spaces. I suggest turning that on...
EDIT: doing a standard find and replace could be dangerous if you're using tabs somewhere else for any reason.
If you look here, there's an option called "tabify region". That might be more interesting for you.

There should be an app for that. ;)
If you enjoy overkill, what about running your code through a regular expression like:
re.sub('\t', '\s\s\s\s', yourCode)

For those people having the problem, the new version of VSCode can solve this easily.
Click on Tab Sizes at the bottom of the page.
Select Convert Indentation to Spaces from the "Select Action" menu that pops up.

Related

vscode python avoid indent of multiline string

So here is an example of a multiline string in vscode/python:
Cursor is after the p , and then you press enter, and end up like this:
i.e. the string ends up indented, which seems what you almost never want - why have an arbitratly amount of whitespace on the next line of this string ?
Is there any way change this in vscode, i.e. for multiline strings, it should end up with this:
I think this problem is related to different coding styles of different people.
For example,
def example(x):
if x:
a = '''
This is help
'''
def example(x):
if x:
a = '''This is help
'''
The automatic indenting of vscode line breaks is based on code blocks. If you want Vscode can identify multiline string, I think it would be better to submit future request in github. I've submitted this issue for you.
I am not 100% sure if what OP meant is just to refer to the indentation in the editor (namely, VSC) or if, by this:
i.e. the string ends up indented, which seems what you almost never want - why have an arbitrary amount of white space on the next line of this string?
...they also meant to refer to the actual output of the multi-line string,
(or also, just in case anybody else finds this post looking for a way to avoid this affecting the actual output of the multi-line string), I'd like to add as a complementary answer (cannot comment yet) that this was already beautifully answered here.
If that's the case and you're reading this for that reason, in short, all you want is to import the standard lib 'inspect' and post-process your string with it, using the cleandoc method.
Without breaking the indentation in your IDE, this method makes sure to give you the string output you actually expected:
All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.
(From the docs link above)
Hope that helps anyone.

why in the Python interpreter the first indentation level is set to 4 space, while the second to 8?

let's take the really simple case of two nested for loops
after pressing return and tab the first time, I get an indentation level where 1 tab equals 4 spaces
after pressing return and tab the second time, I get an indentation level where 1 tab equals 9 spaces
this is rather annoying when I want to copy a piece of code from a script and run it on the interpreter, as it returns the
TabError: inconsistent use of tabs and spaces in indentation
I did some googling but you can imagine what the keywords "python", "interpreter", "indentation" returns: nothing useful
Is there a way to correct this? Thanks
EDIT
just try yourselves:
open a terminal
run python command
then type for i in range(3):
press Enter
then press Tab once, to get to the right indentation level
then type for j in range(3):
press Enter again
then press Tab twice, to get to the (expected) indentation level
if, like me, you have a Mac, chances are that the second Tab hit in the last step above, will yield 8 spaces, instead of 4
This causes problems when copying lines of code written with an IDE
(I'm using Sublime 3, with the option translate_tabs_to_spaces set to True)
I was hoping someone could identify some flag/options/setting of my interpreter which could solve this issue
Title question :
Because you are at 2nd indentation level since you have a loop inside a loop.
Tabulation/space error :
Python uses only indentation to interpret which block belongs to the code. No "BEGIN...END" , no brackets. So indentation IS information.
The rule is "indentation must be uniform", so either everything is spaces (1,2,4.. as you want) or everything is tabulations.
For more information, refer to the Python style guideline (PEP8) here :
https://www.python.org/dev/peps/pep-0008/
By using an IDE ( such as Spyder, for example) tabs will automatically be replaced by spaces. I recommend you to use one, especially if you are a new to python.

I dont understand the improper uses of spaces and tabs in indentation error in my code [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed last month.
I'm trying to create an application in Python 3.2 and I use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when I try to run the program.
How can I change the spaces into tabs? It's driving me crazy.
import random
attraktioner = ["frittfall","bergodalbana","spökhuset"]
class Nojesfalt:
def __init__(self, attraktion):
self.val = attraktion
self.langd = 0
self.alder = 0
#längdgräns för fritt fall
def langdgrans(self):
print("")
self.langd = int(input("Hur lång är du i cm? "))
if self.langd < 140:
print("tyvärr, du är för kort, prova något annat")
return 0
elif self.langd >= 140:
print("håll dig hatten, nu åker vi!")
print(" ")
return 1
#åldersgräns för spökhuset
def aldersgrans(self):
print("")
self.alder = int(input("Hur gammal är du? "))
if self.alder < 10:
print("tyvärr, du är för ung, prova något annat")
return 0
elif self.alder >= 10:
print("Gå in om du törs!")
print(" ")
return 1
#åker attraktion frittfall lr bergodalbana
def aka(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("åkturen gick åt skogen, bättre lycka nästa gång")
elif tal >= 20:
print("jabbadabbbadoooooooo")
return 1
#går i spökhuset
def aka1(self):
print("")
print(self.val)
tal = random.randint(0,100)
if tal < 20:
print("du är omringad av spöken och kan inte fortsätta") return 0
elif tal >= 20:
print("Buhuuuuuu, buuuhuuuu")
return 1
#programkod
print("Välkommen till nöjesfältet, vad vill du göra?")
print(" ")
while 1:
vald_attr = input("Vad vill du göra?\n1. frittfall\n2. bergodalbana\n3. spökhuset\n4. Avsluta\n")
if vald_attr == "1":
val = Nojesfalt(attraktioner[0])
if val.langdgrans() == 1:
val.aka()
elif vald_attr == "2":
val = Nojesfalt(attraktioner[1])
val.aka()
elif vald_attr == "3":
val = Nojesfalt(attraktioner[2])
if val.aldersgrans() == 1:
val.aka1()
elif vald_attr == "4":
break
Don't use tabs.
Set your editor to use 4 spaces for indentation.
Make a search and replace to replace all tabs with 4 spaces.
Make sure your editor is set to display tabs as 8 spaces.
Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally - such as when copying and pasting from example code that uses tabs instead of spaces.
For VSCode users
Ctrl+Shift+P or View->Command Palette.
Type
>Convert Indentation to Spaces
press Enter.
Using the autopep8 command below fixed it for me:
autopep8 -i my_file.py
Documentation for autopep8 linked here.
With the IDLE editor you can use this:
Menu Edit → Select All
Menu Format → Untabify Region
Assuming your editor has replaced 8 spaces with a tab, enter 8 into the input box.
Hit select, and it fixes the entire document.
When using the sublime text editor, I was able to select the segment of my code that was giving me the inconsistent use of tabs and spaces in indentation error and select:
view > indentation > convert indentation to spaces
which resolved the issue for me.
It is possible to solve this problem using notepad++ by replacing Tabs with 4 Spaces:
Choose Search -> Find... or press Ctrl + F
Select the Replace tab
In the box named Search Mode choose Extended(\n, \r, \t, \0, \x...)
In the field Find what : write \t
In the field Replace with : press Space 4 times. Be sure that there is nothing else in this field.
Click on the button Replace All
Generally, people prefer indenting with space. It's more consistent across editors, resulting in fewer mismatches of this sort. However, you are allowed to indent with tab. It's your choice; however, you should be aware that the standard of 8 spaces per tab is a bit wide.
Concerning your issue, most probably, your editor messed up. To convert tab to space is really editor-dependent.
On Emacs, for example, you can call the method 'untabify'.
On command line, you can use a sed line (adapt the number of spaces to whatever pleases you):
sed -e 's;\t; ;' < yourFile.py > yourNedFile.py
If you are using Sublime Text for Python development, you can avoid the error by using the package Anaconda. After installing Anaconda, open your file in Sublime Text, right click on the open spaces → choose Anaconda → click on autoformat. Done. Or press Ctrl + Alt + R.
Sublime Text 3
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I recently had the same problem and found out that I just needed to convert the .py file's charset to UTF-8 as that's the set Python 3 uses.
BTW, I used 4-space tabs all the time, so the problem wasn't caused by them.
What I did when the same error popped up: Select everything (Str + A) and press Shift + Tab. So nothing was indented anymore. Now go back to the lines you want to have indented, and put it back how you want it.
It worked for me...
If you use ATOM:
Go to Menu: Packages --> WhiteSpace --> Convert all Tabs to Spaces
Try deleting the indents and then systematically either pressing tab or pressing space 4 times. This usually happens to me when I have an indent using the tab key and then use the space key in the next line.
Your problem is due to your editor limitations/configuration. Some editors provide you of tools to help with the problem by:
Converting tabs into spaces
For example, if you are using Stani's Python editor you can configure it to do it on saving.
Converting spaces into tabs
If you are using ActiveState Komodo you have a tool to 'tabify' your code. As others already pointed, this is not a good idea.
Eclipse's Pydev provides functions "Convert tabs to space-tabs" and "Convert space-tabs to tabs".
I use Notepad++ and got this error.
In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.
To solve the problem, I just deleted the tab before the line then added four spaces.
There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:
Then if your code is using spaces, you will see small dots where your code is indented:
And if it is indented using tabs, you will see something like this:
Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,
I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.
SOULUTION FOR SUBLIME TEXT
My Solution to this problem was to open it in idle editor and then idle editor will uncover your problem
e.g
SUBLIME TEXT
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
IDLE EDITOR
while run:
clock.tick(27)
milli = clock.tick()
seconds = milli/1000
timeForLevel += seconds
print(timeForLevel)
I am not saying that you should only use idle editor. I'm saying that if you get that error you should check idle editor
I had the same error. I had to add several code lines to an existing *.py file. In Notepad++ it did not work.
After adding the code lines and saving, I got the same error. When I opened the same file in PyCharm and added the lines, the error disappeared.
I oddly ran into a similar issue with one of my .py files. I simply opened the file in Pycharm and pressed Option+Command+L which correctly formats the file contents in one go.
I suspect I was having trouble because I coded this particular .py file through jupyter labs as opposed to my usual choice of sublime text or Pycharm and therefore ran into some hidden indentation issues many answers here have alluded to
Use pylint it will give you a detailed report about how many spaces you need and where.
The following trick has worked for me:
Copy and paste the code in the notepad.
Then from the notepad again select all and copy the code
Paste in my views.py
Select all the newly pasted code in the views.py and remove all the tabs by pressing shift+tab from the keyboard
Now use the tab key again to use the proper indentation
For Anaconda, Spyder users you can go to Source> Fix indentation
If your editor doesn't recognize tabs when doing a search and replace (like SciTE), you can paste the code into Word and search using Ctr-H and ^t which finds the tabs which then can be replace with 4 spaces.
Solving this using Vim editor
Open terminal (Ctrl + Alt + T).
Go to the directory where the file is located (cd <path_to_your_directory>). Ex: cd /home/vineeshvs/work.
Open the file in Vim (vim <file_name>). Ex: vim myfile.txt .
[Optional step] Enable search keyword highlighting in Vim (ESC :set hlsearch)
Go to the line where you have this problem (ESC :<line_number>). Ex: :53 in Vim editor after pressing ESC button once.
Replace tabs using the required number of spaces in Vim (:.,$s/\t/<give_as_many_spaces_as_you_want_to_replace_tab>/gc). Ex: Tab will be replaced with four spaces using the following command: :.,$s/\t/ /gc after pressing ESC button once). This process is interactive. You may give y to replace the tab with spaces and n to skip a particular replacement. Press ESC when you are done with the required replacements.
Well I had the same problem and I realised that the problem is that I copied code from another python editor to sublime.
I was working with jupyter notebook and then I copied the code into sublime. Apparently when you make specific modifications (like moving code in functions) then indentation gets messy and this is where the problem comes from.
So just stick to one editor. If you do so, then you will be having no problem.
For Jupyter users:
CTRL + Shift + P Automatically idents the selection:
While the original question is about self authored code, the search engines lead here for when searching for the title string. An error message one might very likely get when attempting to make use of an already existing library or tool.
For those finding their way here when attempting to use someone elses code; It is a python2 vs. python3 thing, according to Tab Error in Python (an answer which also refers to the relevant section of the PEP8 styleguide.
I got the same errors but could not figure out what I was doing wrong.
So I fixed it by running auto-indent on my code and allowing the machine to fix my fault.
If anyone is wondering how I did that.
Simple.
Go in vim.
Type in G=gg.
This will automatically fix everything. Good luck :)
Sometimes, tab does mess up while indenting. One way is to obviously use the tab and backspace to correctly indent the code.
Another way is to use space 4 times (depending on how much you want to indent).
A weird way that worked for me when nothing else worked, whichever line I getting the error, I backspaced that line to the previous line and then pressed enter. It automatically indented the line to correct position and I was not getting any error after that.
Hopefully, this should help.

indent python file (with pydev) in eclipse

I'm a newbie in eclipse. I want to indent all the lines of my code and formatting the open file by pressing a shortcut or something like that...
I know the CTRL+SHIFT+F (as it actually doesn't work in pydev!!)
I've been searching for hours with no success. Is there any way to do that in eclipse. kind of like CTRL+K,D in visual studio, which formats and indents all the source code lines automatically?
If you want to change from 2 space to 4 space indentation (for instance), use "Source->Convert space to tab" with 2 spaces, then "Soruce->Convert tab to space" with 4 spaces.
I ... don't think this question makes sense. Indentation is syntax in Python. It doesn't make sense to have your IDE auto-indent your code. If it's not indented properly already, it doesn't work, and the IDE can't know where your indentation blocks begin and end. Take, for example:
# Valid Code
for i in range(10):
b = i
for j in range(b):
c = j
# Also Valid Code.
for i in range(10):
b = i
for j in range(b):
c = j
There's no possible way that the IDE can know which of those is the correct version, or what your intent is. If you're going to write Python code, you're going to have to learn to manage the indentation. There's no way to avoid it, and expecting the IDE to magically clean it up and still get the desired result out of it is pretty much impossible.
Further example:
# Valid Code.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
# Again, also valid code, wildly different behavior.
outputData = []
for i in range(100):
outputData.append(str(i))
print ''.join(outputData)
The first will produce a list of strings, then print the joined result to the console 1 time. The second will still produce a list of strings, but prints the cumulative joined result for each iteration of the loop - 100 print statements. The two are both 100% syntactically correct. There's no problem with them. Either of them could be what the developer wanted. An IDE can't "know" which is correct. It could, very easily incorrectly change the first version to the second version. Because the Language uses Indentation as Syntax, there is no way to configure an IDE to perform this kind of formatting for you.
Although auto-indentation is not a feature of PyDev because of the language design you should be able to indent with a simple tab. Just select the lines you want to indent and press Tab. If you want to unindent lines you have to press Shift+Tab.
Thats all.
It is much easier:
Select multiple lines
Press Tab to indent (move right), Shift + Tab to unindent (move left) all selected
lines.
Indentation is syntactically significant; consider the difference between
for i in range(5):
print i
print "done"
and
for i in range(5):
print i
print "done"
However, it certainly makes sense for the IDE to be able to normalize the existing indentation (e.g. apply a consistent number of spaces/tabs at each level).
Currently PyDev does not support such a feature; Pydev author Fabioz at one point expressed interest in adding it in the future and indicated that for now you can use the supplied reindent.py script to do it.
Obviously this is only for Pydev, but I've worked out that you can get the very useful functions "Shift Right" and "Shift Left" (mapped by default to CTRL + ALT + . and CTRL + ALT + ,) to become useful by changing their keybindings to "Pydev Editor Scope" from "Pydev View". This effectively indents/dedents all lines that you've selected as much as you'd like
I think that what you're looking for is some kind of shortcut in Eclipse/PyDev so that the selected code can be idented all at once. Just like when you create a new "if" or a "for" loop above a block of code and then need to rearrange the identation. The IDLE Editor has the "Ctrl + ]" shortcut that works exactly that way. It seems that the PyDev in Eclipse doesnt have something like that as far as I know.
One can also select the lines, right click, then shift right / shift left
It seems source formatting is still not available in PyDev.
For one off instances I found this web app does the job nicely.
http://pythoniter.appspot.com/
Like earlier said python requires to indent your code, so for other things like: space between variables passed as arguments to methods, etc., one can use ctrl+shift+f to format the code. This what is used for java, I tried for pydev and does some formatting.

vim highlighting everything in red

I added a print line to a python script while the script was executing, and now all the text is highlighted in red when I open the file. Opening and closing the file doesn't get rid of it. Opening a second python file momentarily fixed the problem, but then closing file and reopening brought the problem back. Now it wont go away at all. Any body know what could cause this?
This happens sometimes in vim when it goes to highlight syntax on multi-line comments. Occasionally everything after the multi-line comment also becomes colored the same as the comment.
I am unsure whether this is a legit bug in vim, or in the actual syntax settings for Python (e.g. python.vim), but I definitely experience this from time-to-time.
For a quick fix, you might try typing:
:hi Error NONE
And then hit Enter.
Old thread, but hope this helps.
By mistake I did a "/." on my vim screen, which highlighted all lines in red. If I open any other file, the red highlighting stays.
Try searching for some other keyword, let's say "/word" - doesn't matter word exists or not. It restores the color.
You probably have an unterminated multiline string. They start and end with either three single or three double quotes.
''' <== this is the start of a multiline string
this is still in the string
this is the last line '''
As per this article http://vim.wikia.com/wiki/Fix_syntax_highlighting, I mapped F12 to resync the syntax highlighting from the start of the file. It has worked better in some instances where <ctrl-l> didn't.
noremap <F12> <Esc>:syntax sync fromstart<CR>
inoremap <F12> <C-o>:syntax sync fromstart<CR>

Categories

Resources