A pythonic way to insert a space before capital letters

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

    I agree that the regex solution is the easiest, but I wouldn't say it's the most pythonic.

    How about:

    text = 'WordWordWord'
    new_text = ''
    
    for i, letter in enumerate(text):
        if i and letter.isupper():
            new_text += ' '
    
        new_text += letter
    

提交回复
热议问题