2
"CIA is a top secret...".title()

yields:

Cia Is A Top Secret...

Is there any hidden functionality somewhere to keep already capital letters capitalized so I would get:

CIA Is A Top Secret...

instead? or do I have to write it myself?

JasonGenX
  • 4,952
  • 27
  • 106
  • 198
  • 1
    This answer seems to have what you are looking for https://stackoverflow.com/questions/1549641/how-to-capitalize-the-first-letter-of-each-word-in-a-string-python/1549983#1549983 –  Sep 11 '19 at 20:43

2 Answers2

1

You can write your own- something along this lines:

def title_but_keep_all_caps(text, slow = False):
    """Replaces words with title() version - excempt if they are all-caps.
    The 'slow = False' way replaces consecutive whitespaces with one space,
    the 'slow = True' respects original whitespaces but creates throwaway strings."""
    if slow:
        t = ' '.join( (org.title() if any(c.islower() for c in org) 
                                   else org for org in text.split()) )
    else:
        t = text
        p = {org:org.title() if any(c.islower() for c in org) 
                             else org for org in text.split()}
        for old,new in p.items():
            t =  t.replace(old,new)   # keeps original whitespaces but is slower

    return t


example ="CIA is a        top secret   agency..."
print(title_but_keep_all_caps(example))
print(title_but_keep_all_caps(example,True))

Output:

CIA Is A        Top Secret   Agency...
CIA Is A Top Secret Agency...
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0
def title_with_caps(string):
    return ' '.join([w.title() if w.islower() else w for w in string.split()])
JasonGenX
  • 4,952
  • 27
  • 106
  • 198
  • This is fine but lacks `title`'s effect of normalizing the case of words in some instances. If you had a typo like `thIs` in your data it wouldn't catch it. – Two-Bit Alchemist Sep 11 '19 at 21:01
  • What if you just tested `w[0].islower()`? – Two-Bit Alchemist Sep 11 '19 at 21:06
  • That's correct. I guess I can compensate by separating out the words that have FULL UPPER CASE spelling. do the standard .title() and then paste those words back in the string, so to speak. – JasonGenX Sep 11 '19 at 21:06