s = "HiMyNameIsBob"
letters = ("A","B", "C", "D"...)
for char in s:
if s.find(letters) is True:
我想要的结果是如何在字符串中拆分大写字母?
"Hi My Name Is Bob"
我想避免使用正则表达式的方法
s = "HiMyNameIsBob"
letters = ("A","B", "C", "D"...)
for char in s:
if s.find(letters) is True:
我想要的结果是如何在字符串中拆分大写字母?
"Hi My Name Is Bob"
我想避免使用正则表达式的方法
我可能依赖字符串的词典式排序位置:
''.join(' '+x if 'A' <= x <= 'Z' else x for x in s)
演示:
>>> s = "HiMyNameIsBob"
>>> ''.join(' '+x if 'A' <= x <= 'Z' else x for x in s)
' Hi My Name Is Bob'
如果你不想要领先空间,你总是可以得到.strip()
的结果。
稍微更好的方法来检查,如果字符是大写是通过使用isupper()
功能(感谢唯美主义者和WIM指出这一点):
>>> ''.join(' '+x if x.isupper() else x for x in s)
' Hi My Name Is Bob'
>>> s = "HiMyNameIsBob"
>>> t = ''.join(c for c in s if c.isupper())
>>> print t
HMNIB
import sys
s = "HiMyNameIsBob"
letters = ("A","B", "C", "D"...)
for char in s:
if s.find(letters):
sys.stdout.write(' ')
sys.stdout.write(char)
>>> re.sub('([A-Z])',' \g<1>', "HiMyNameIsBob").strip()
'Hi My Name Is Bob'
OP说使用正则表达式avdoid – Mark 2013-02-14 10:23:55
+1,虽然我觉得'str.islower()'是好得多的选择这里。 – Aesthete 2013-02-13 01:37:03
@Aesthete - 更好。它比我在'set(string.ascii_lowercase)'中使用的编辑更好。在此之前,我不知道'str.islower' :) – mgilson 2013-02-13 01:39:58
添加一个'.strip()',你真是太棒了! – Aesthete 2013-02-13 01:40:45