Python Forum
how far is this line indented?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how far is this line indented?
#1
i get a line of data that may be indented much like Python code. i have bad code that tries things to see how much indentation there is. in C i could just step through the line and count the spaces until a non-space or the end of the line. i need to process tons of this kind of data over and over (a new format for genealogical data) so i've going through my code to speed things up. i'm looking at the indent counters and wondering if there is something better. sorry, no code samples of many bad ways. but the task is simple to describe: given a string (or bytes) how many spaces does it indent with. anything built-in that could speed this up?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
>>> import re
>>> x = "     some letters"
>>> print(len(re.match(r" *", x).group()))
5
>>> x1 = x.lstrip(" ")
>>> print (len(x) - len(x.lstrip(" ")))
5
Skaperen likes this post
Reply
#3
import re

# For efficiency reasons: compile only once.
initial_spaces = re.compile(r"^( *)")
# Meaning:
#  ^ : matches the start of a line.
#  ( ... ) : capture this part of the line (as match object 1).
#  <space> : matches a space.
#  * : previous char (i.c. space) repeated zero or more times.

# Some file with indented lines.
with open("forum05.py", "r") as source:
    for line in source:
        indentation = re.search(initial_spaces, line)
        # Show the end position of match object nr 1. (Object 0 is the whole line.)
        print(indentation.end(1))
Output:
0 0 0 0 0 0 0 0 0 0 0 0 4 8 8 8 8
I hope the indentation consists of spaces only, or else you would have to replace tabs in a line with spaces (8 or 4) first.
Skaperen likes this post
Reply
#4
they are spaces only. this new format i am creating is inspired by Python. need it smaller? use compression (smaller than tabs and Python can read or write it that way with a select compression).
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to write in text file - indented block Joni_Engr 4 6,440 Jul-18-2022, 09:09 AM
Last Post: Hathemand
  error "IndentationError: expected an indented block" axa 4 2,910 Sep-08-2020, 02:09 PM
Last Post: ibreeden
  IndentationError: expected an indented block ryder5227 2 2,600 Sep-27-2019, 06:59 PM
Last Post: jefsummers
  [SOLVED] Expected An Indented Block Panda 4 6,002 Jun-06-2018, 09:57 PM
Last Post: Larz60+
  Expected an indented block Nicoles07 2 3,415 Sep-15-2017, 05:19 PM
Last Post: deaspo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020