[Tutor] Splitting at a capital letter in a string

Jacob S. keridee at jayco.net
Wed Nov 3 23:41:07 CET 2004


>Yep. re looks like the only way. I was just wondering if I was missing
>something in String.

I'm sorry, but I prefer to disagree. Consider this code sample.

[start of code]

a = "HiImAStringWithCaps"
seperator = " "
a = list(a)
x = 0
while x < len(a):
    if a[x] == a[x].upper():  # This is number 4
        a.insert(x,seperator)
        x = x+1
    x = x+1
a = "".join(a).lstrip(seperator)
print a

[end of code]

The stuff goin' down here is
1) We define a
2) We define the seperator - You said in the email it would be a space
3) We convert the string a into a list so we can mess with each item in
there
4) Next, we run through the list and search for uppercase letters. Fancy way
of doing so, don't you think?
5) Then, we insert the seperator at that index
6) We increment x an extra 1 because we added an index (the seperator)
7) After all that's done, we join the list together into and string and
strip the seperator off of the beginning

How about that!  I did it without the re module.

HTH,
Jacob Schmidt



More information about the Tutor mailing list