Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Is there any way to split the string if it contains an uppercase letter but not the first letter?

For example, given "RegularExpression" I would like to obtain "Regular Expression".

I tried the following regex to solve it:

re.sub("[a-z]{1}[A-Z][a-z]{1}", " ","regularExpress") 

But this deletes the matching pattern:

regular press

Should I prefer the regex solution or is there any other solution to it?

1 Answer

0 votes
by (36.8k points)
edited by

You can do this by using the following code:

import re

s = "RegularExpression"

re.sub(r"([A-Z][a-z]+)([A-Z][a-z]+)", r"\1 \2", s)

which means "put a space between first match group and second match group", where match groups are the cap followed by one or more non-caps.

If you are a beginner and want to know more about Python the do check out the Data Science with Python Course

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...