A pythonic way to insert a space before capital letters

前端 未结 9 2018
旧时难觅i
旧时难觅i 2021-02-04 00:32

I\'ve got a file whose format I\'m altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital l

9条回答
  •  青春惊慌失措
    2021-02-04 00:55

    I think regexes are the way to go here, but just to give a pure python version without (hopefully) any of the problems ΤΖΩΤΖΙΟΥ has pointed out:

    def splitCaps(s):
        result = []
        for ch, next in window(s+" ", 2):
            result.append(ch)
            if next.isupper() and not ch.isspace():
                result.append(' ')
        return ''.join(result)
    

    window() is a utility function I use to operate on a sliding window of items, defined as:

    import collections, itertools
    
    def window(it, winsize, step=1):
        it=iter(it)  # Ensure we have an iterator
        l=collections.deque(itertools.islice(it, winsize))
        while 1:  # Continue till StopIteration gets raised.
            yield tuple(l)
            for i in range(step):
                l.append(it.next())
                l.popleft()
    

提交回复
热议问题