Python:在大写字母前面的字符串中预加空格的有效方法



在Python中将以下字符串转换为预期字符串的最佳方法是什么。

  1. "PowerEdgeSystem"=>Power Edge System
  2. CCD_ 3=>VMware System
  3. CCD_ 5=>VMware System EQUIPMENT

已尝试:

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

第一个字符串是好的,但不如第二个字符串好。尽管如此,我们仍然可以检查特定字符"两侧"的情况,并在此基础上添加空间,如下所示,

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

但代码会变得更加混乱。我期待一些更明确的方式(如果有的话(。谢谢你,

我想你会想要这样的东西,使用正则表达式:

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

不幸的是,这在"VMwareSystem"上没有成功。

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

您可以使用一个正则表达式来替换它,贪婪地匹配至少一个非大写字符,然后在它们之间插入一个空格:

>>> 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'

最新更新