首页 > 解决方案 > Python 字符串中的 .title()

问题描述

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

产量:

Cia Is A Top Secret...

是否有任何隐藏的功能可以保持大写字母大写,所以我会得到:

CIA Is A Top Secret...

反而?还是我必须自己写?

标签: python-3.x

解决方案


您可以按照以下方式编写自己的内容:

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))

输出:

CIA Is A        Top Secret   Agency...
CIA Is A Top Secret Agency...

推荐阅读