Python Title Case,但保留预先存在的大写

use*_*306 4 python regex python-3.x

我正在寻找一种非常pythonic的方式(Python 3.x)做下面的事情,但尚未提出一个.如果我有以下字符串:

string = 'this is a test string'
Run Code Online (Sandbox Code Playgroud)

我可以用它来标题:

string.title()
Run Code Online (Sandbox Code Playgroud)

结果如下:

'This Is A Test String'
Run Code Online (Sandbox Code Playgroud)

但是,如果我有以下字符串,我想转换:

string = 'Born in the USA'
Run Code Online (Sandbox Code Playgroud)

应用标题案例会导致:

string = 'Born In The Usa'
Run Code Online (Sandbox Code Playgroud)

应该导致:

'Born In The USA'
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来做一个标题案例,但不是调整现有的大写文本.有没有办法做到这一点?

Mar*_*ers 8

目前还不清楚你期望的输出是什么.

如果你想忽略整个字符串,因为它包含大写单词,请先测试字符串是否为小写:

if string.islower():
    string = string.title()
Run Code Online (Sandbox Code Playgroud)

如果您只想忽略已经包含大写字母的特定单词,请在空格上拆分字符串,并仅选择小写字母:

string = ' '.join([w.title() if w.islower() else w for w in string.split()])
Run Code Online (Sandbox Code Playgroud)

演示后一种方法:

>>> string = 'Born in the USA'
>>> ' '.join([w.title() if w.islower() else w for w in string.split()])
'Born In The USA'
Run Code Online (Sandbox Code Playgroud)