简体   繁体   中英

how to indent block of python code without using tabs

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

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.

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.

I personally use Sublime Text and there seems to be an option to customize Tabs:

{ "tab_size": 4, "translate_tabs_to_spaces": true }

In the Packages/User/Preferences.sublime-settings. Maybe worth trying that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM