2

How can I use regex to count the number of spaces beginning of the string. For example:

string = ' area border router'

count_space variable would return me a value of 1 since there is 1 whitespace at the beginning of the string. If my string is:

string = '  router ospf 1'

count_space variable would return me a value of 2 since there is 2 whitespace at the beginning of the string. And so on....

I thing the expression would be something like RE = '^\s' ? But not sure how to formulate it.

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
python_newbie
  • 111
  • 1
  • 9
  • Nevermind! I found someone that has the answer. https://stackoverflow.com/questions/13241399/check-string-indentation – python_newbie Aug 04 '18 at 03:02
  • Another Possible duplicate: [Returning the lowest index for the first non whitespace character in a string in Python](http://stackoverflow.com/questions/2378962/returning-the-lowest-index-for-the-first-non-whitespace-character-in-a-string-in) – U13-Forward Aug 04 '18 at 03:05

1 Answers1

1

You don't need regex, you can just do this:

s = ' area border router'
print(len(s)-len(s.lstrip()))

Output:

1
U13-Forward
  • 69,221
  • 14
  • 89
  • 114