How can I indent a string when lowercase meets uppercase, like in thisSentence?

Viewed 34

I frequently get strings that are formatted like this:

"This is an exampleI wish it looked different"

when I want it to look like this instead:

"this is an example

I wish it looked different"

Any ideas? Regular expressions maybe? I'm still very noob, many thanks in advance!

1 Answers

Should be pretty simple for your example with re.sub:

import re
old_string = "This is an exampleI wish it looked different"
new_string = re.sub('([a-z])([A-Z])', '\\1\n\\2', old_string)
print(new_string)
# This is an example
# I wish it looked different

It finds all parts where a lowercase letter is followed by an uppercase letter and puts a newline between them.

Related