Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split leading whitespace from rest of string

I'm not sure how to exactly convey what I'm trying to do, but I'm trying to create a function to split off a part of my string (the leading whitespace) so that I can edit it with different parts of my script, then add it again to my string after it has been altered.

So lets say I have the string:

"    That's four spaces"

I want to split it so I end up with:

"    " and "That's four spaces"

2 Answers

You can use re.match:

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

(\s*) captures zero or more whitespace characters at the start of the string and (.*) gets everything else.

Remember though that strings are immutable in Python. Technically, you cannot edit their contents; you can only create new string objects.


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

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

The main tools here are next, enumerate, and a generator expression. This solution is probably faster than the Regex one, but I personally think that the first is more elegant.

Why don't you try matching instead of splitting?

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

Explanation:

  • ^\s+ Matches one or more spaces at the start of a line.
  • | OR
  • .+ Matches all the remaining characters.
like image 24
Avinash Raj Avatar answered Jan 19 '26 15:01

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!