Jai K
Jai K

Reputation: 395

Python: Efficient way to prepend a space in a string before of upper case letter

What is the best way to convert the following string to the expected string in Python.

  1. "PowerEdgeSystem" => Power Edge System
  2. "VMwareSystem" => VMware System
  3. VMwareSystemEQUIPMENT => VMware System EQUIPMENT

Tried:

s = 'PowerEdgeSystem'
s = ''.join([' ' + c if i != 0 and c.isupper() else c for i, c in enumerate(s)])

First string is fine, but not as good for second string. Still we can check the case of 'both' side of the particular character and add space based on that as below,

s = ''.join([' ' + c if i != 0 and c.isupper() and not c[i+1].isupper() else c for i, c in enumerate(s)])

But the code will become more messy. I'm expecting some thing more clear way (if anything available). Thank you,

Upvotes: 1

Views: 90

Answers (2)

Jose Henrique Roveda
Jose Henrique Roveda

Reputation: 180

I think you will want something like this, using Regular expression:

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

Unfortunately this does not succeed on "VMwareSystem".

>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "VMwareSystem")
'V Mware System'

Upvotes: 3

Ruzihm
Ruzihm

Reputation: 20259

You can use a regular expression with substitution for this, greedily matching at least one non-uppercase character followed by at least one uppercase character, then inserting a space in between:

>>> matchPattern = r"([^A-Z]+)([A-Z]+)"
>>> replacePattern = r"\1 \2"
>>> re.sub(matchPattern, replacePattern, "VMwareSystemVMwareSystem")
'VMware System VMware System'
>>> re.sub(matchPattern, replacePattern, "PowerEdgeSystem")
'Power Edge System'

Upvotes: 1

Related Questions