A pythonic way to insert a space before capital letters

前端 未结 9 1858
旧时难觅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:57

    If you have acronyms, you probably do not want spaces between them. This two-stage regex will keep acronyms intact (and also treat punctuation and other non-uppercase letters as something to add a space on):

    re_outer = re.compile(r'([^A-Z ])([A-Z])')
    re_inner = re.compile(r'(?<!^)([A-Z])([^A-Z])')
    re_outer.sub(r'\1 \2', re_inner.sub(r' \1\2', 'DaveIsAFKRightNow!Cool'))
    

    The output will be: 'Dave Is AFK Right Now! Cool'

    0 讨论(0)
  • 2021-02-04 00:58

    Perhaps shorter:

    >>> re.sub(r"\B([A-Z])", r" \1", "DoIThinkThisIsABetterAnswer?")
    
    0 讨论(0)
  • 2021-02-04 00:59

    If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced.

    >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord")
    'Word Word WW WW WW Word'
    

    A look-behind would solve this:

    >>> re.sub(r"(?<=\w)([A-Z])", r" \1", "WordWordWWWWWWWord")
    'Word Word W W W W W W Word'
    
    0 讨论(0)
提交回复
热议问题