"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?
"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?
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...
def title_with_caps(string):
return ' '.join([w.title() if w.islower() else w for w in string.split()])