Function to return space separated string

Is there an existing function in Python that works like .strip()

/ .lstrip()

/ .rstrip()

do, but returns trapped whitespace instead, rather than the resulting split string?

Namely:

test_str = '\n\ttext goes here'
test_str.lstrip() # yields 'text goes here'
test_str.lwhite() # yields '\n\t'

      

Where .white()

, .lwhite()

and .rwhite()

are those functions that I hope exist. Otherwise, I'll have to work with regex and captured groups:

^(\s*).*(\s*)$    for .white()
^(\s*)            for .lwhite()
(\s*)$            for .rwhite()

      

To give a better example, Python has methods .strip()

that strip leading and trailing whitespace from a given string and return a stripped string. It's the same with Python methods .lstrip()

and .rstrip()

only for the beginning and end respectively.

I'm looking for a way to get back the spaces that have been removed from the ends of the line. So, for a line like the following ...

sample = '\n\t this string\t is \n \ta sample\t!\n'

      

... I would like to return '\n\t '

for the original version, '\n'

for the final version, or in the list returned for the full version.

Thanks everyone!

+3


source to share


2 answers


Oops, I just figured out that you named the strip instead of split, so here itertools.takewhile

:

from itertools import takewhile

def lstripped(s):
    return ''.join(takewhile(str.isspace, s))

def rstripped(s):
    return ''.join(reversed(tuple(takewhile(str.isspace, reversed(s)))))

def stripped(s):
    return lstripped(s), rstripped(s)

      



polyfill for itertools.takewhile

looks like this:

def takewhile(predicate, iterable):
    # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
    for x in iterable:
        if predicate(x):
            yield x
        else:
            break

      

+1


source


I probably take your words literally, but if you only want to get spaces in your line, then do you understand the transition method?



In [112]: x
Out[112]: '\n\ttext goes here'

In [113]: ''.join([i for i in x if not i.isalnum()]).replace(" ",'')
Out[113]: '\n\t'

      

+1


source







All Articles