user2016535
user2016535

Reputation: 13

How to split uppercase letters within a string?

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

Answers (4)

Dmitry Dubovitsky
Dmitry Dubovitsky

Reputation: 2236

>>> re.sub('([A-Z])',' \g<1>', "HiMyNameIsBob").strip()
'Hi My Name Is Bob'

Upvotes: 0

mgilson
mgilson

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

Josh Austin
Josh Austin

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

Kyle Maxwell
Kyle Maxwell

Reputation: 627

You want str.isupper().

>>> s = "HiMyNameIsBob"
>>> t = ''.join(c for c in s if c.isupper())
>>> print t
HMNIB

Upvotes: 2

Related Questions