Strip leading spaces from the rest of the line

I'm not sure how exactly to convey what I am trying to do, but I am trying to create a function to split part of my line (leading space) so that I can edit it with different parts of my script, then add it again to my line after of how it was changed.

So, let's say I have a line:

"    That four spaces"

      

I want to break it down so that in the end:

"    " and "That four spaces"

      

+3


source to share


4 answers


You can use re.match

:

>>> import re
>>> re.match('(\s*)(.*)', "    That four spaces").groups()
('    ', "That four spaces")
>>>

      

(\s*)

commits zero or more whitespace characters to the beginning of the string and (.*)

gets everything else.

Remember these lines are immutable in Python. Technically, you cannot edit their content; you can only create new string objects.




For a non-Regex solution, you can try something like this:

>>> mystr = "    That four spaces"
>>> n = next(i for i, c in enumerate(mystr) if c != ' ') # Count spaces at start
>>> (' ' * n, mystr[n:])
('    ', "That four spaces")
>>>

      

The main tools here are next

, enumerate

and generator expression . This solution is probably faster than Regex, but I personally find the first one to be more elegant.

+2


source


Why don't you try combining instead of splitting?

>>> import re
>>> s = "    That four spaces"
>>> re.findall(r'^\s+|.+', s)
['    ', "That four spaces"]

      



Explanation:

  • ^\s+

    Matches one or more spaces at the beginning of a line.
  • |

    OR
  • .+

    Matches all other characters.
+1


source


One solution is to lstrip the string and then figure out how many characters you have removed. Then you can "modify" the string as desired and finish by adding a space back to your string. I don't think this will work fine with tabs, but for spaces, it looks like this will do:

my_string = "    That four spaces"
no_left_whitespace = my_string.lstrip()
modified_string = no_left_whitespace + '!'
index = my_string.index(no_left_whitespace)
final_string = (' ' * index) + modified_string

print(final_string) #     That four spaces!

      

And a simple test to make sure we did it right, which is passing:

assert final_string == my_string + '!'

      

+1


source


One thing you can do is make a list from a string. it

x="    That four spaces"
y=list(x)
z="".join(y[0:4]) #if this is variable you can apply a loop over here to detect spaces from start
k="".join(y[4:])
s=[]
s.append(z)
s.append(k)
print s

      

This is not a regular expression and will not require import

0


source







All Articles