Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to indent block of python code without using tabs

Tags:

python

I am just learning python and need to know how to indent a block of code without using the tab button (because, as I have read, tab should not be used).

Example:

in a simple print function

def test(string):
    print(string)
    print("'" + string + "'")

test('test')

IF now, I want to put the print functions in an if statement

def test(string):
    if len(string) > 2:
        print(string)
        print("'" + string + "'")

test('test')

How can I indent the two print statements without using the 'tab', or having to click on every line and insert 4 spaces? I am very used to selecting all the lines I need to move to the right and pressing tab regardless of program (geany, ipython, notepad++).

I would like to set off following the PEP8 style guide from the introduction into Python.

My concern is not this particular example, but if I have a code block I want to move left or right that is many more lines.

Thanks,

Ivan

like image 357
ivan7707 Avatar asked May 25 '26 17:05

ivan7707


2 Answers

It depends on what text editor you're using. I use Notepad++, which is one of the ones you mention, and it has an option to use spaces in place of tabs. So I just enable that for .py files, then I can indent a block by hitting tab exactly as you're used to (and unindent with shift-tab).

Go to settings > preferences > tab settings, select "python" from the list on the right and check the "replace by space" checkbox. Other text editors that offer the same feature will presumably each have their own way of enabling it, and their own way of making it language-specific.

Be aware that pressing tab to change the indentation of a selection is just a UI convention, albeit a common one. It doesn't work for example in Notepad, where hitting tab while text is highlighted behaves the same as typing anything else: replaces the selection with a tab. If you were using Notepad then I'm pretty sure the answer would be "it's not possible". If you use lots of different editors then I think unfortunately you're going to have to investigate each one in turn.

like image 145
Steve Jessop Avatar answered May 28 '26 08:05

Steve Jessop


As you have mentioned, PEP8 recommends four spaces for each level of indentation. Many text editors allow you to set tabs to be replaced by a certain number of spaces. So in many cases it is still ok to use tab to program in python, just make sure that it is replaced by four spaces.

like image 34
Andrew Johnson Avatar answered May 28 '26 08:05

Andrew Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!