Reputation: 13
s = "HiMyNameIsBob"
letters = ("A","B", "C", "D"...)
for char in s:
if s.find(letters) is True:
I want the result to be
"Hi My Name Is Bob"
I want to avoid using the regex method
Upvotes: 1
Views: 3498
Reputation: 2236
>>> re.sub('([A-Z])',' \g<1>', "HiMyNameIsBob").strip()
'Hi My Name Is Bob'
Upvotes: 0
Reputation: 309929
I might rely on the lexicographical ordering of strings here:
''.join( ' '+x if 'A' <= x <= 'Z' else x for x in s )
Demo:
>>> s = "HiMyNameIsBob"
>>> ''.join( ' '+x if 'A' <= x <= 'Z' else x for x in s )
' Hi My Name Is Bob'
If you don't want the leading space, you can always .strip()
the result.
A slightly nicer way to check if the character is upper-case is by using the isupper()
function (Thanks to Aesthete and wim for pointing this out):
>>> ''.join( ' '+x if x.isupper() else x for x in s )
' Hi My Name Is Bob'
Upvotes: 10
Reputation: 776
import sys
s = "HiMyNameIsBob"
letters = ("A","B", "C", "D"...)
for char in s:
if s.find(letters):
sys.stdout.write(' ')
sys.stdout.write(char)
Upvotes: 0
Reputation: 627
You want str.isupper().
>>> s = "HiMyNameIsBob"
>>> t = ''.join(c for c in s if c.isupper())
>>> print t
HMNIB
Upvotes: 2