Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab a line's whitespace/indention with Python

Basically, if I have a line of text which starts with indention, what's the best way to grab that indention and put it into a variable in Python? For example, if the line is:

\t\tthis line has two tabs of indention

Then it would return '\t\t'. Or, if the line was:

    this line has four spaces of indention

Then it would return four spaces.

So I guess you could say that I just need to strip everything from a string from first non-whitespace character to the end. Thoughts?

like image 990
Mike Crittenden Avatar asked Feb 15 '10 19:02

Mike Crittenden


People also ask

How do you indent a line in Python?

The first line of python code cannot have an indentation. Indentation is mandatory in python to define the blocks of statements. The number of spaces must be uniform in a block of code. It is preferred to use whitespaces instead of tabs to indent in python.

Can you use Tab to indent in Python?

Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs. Python 3 disallows mixing the use of tabs and spaces for indentation. Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

How many spaces is a \t in Python?

Python 3 says: Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix).

How do you print an indent in Python?

We can use \t in the print() function to print the tab correctly in Python.


1 Answers

def whites(a):
return a[0:a.find(a.strip())]

Basically, the my idea is:

  1. Find a strip of starting line
  2. Find a difference between starting line and stripped one
like image 99
woo Avatar answered Oct 08 '22 14:10

woo