I have a text file, where each line may start with a number of tabs, including no tabs. For example, the first line starts with no tab, the second line with 1 tab, and the third line with 2 tabs:
Chapter 1
1
1.1
Chapter 2
1
1.1
Is it possible to get the number of tabs at the beginning of each line, by using Python?
Using
re.findall,mapandlen:Or from a file:
Note that the
MULTILINE(M) flag is required to match each line start. Also the use of the zero-or-more quantifier (*) ensures matching all starts, even to return an empty string.regex demo
Regex-less variant with
itertools.takewhile:Output:
[0, 1, 2, 0, 1, 2]Used input for the first approach: