带撇号的Python title()

2024-04-29 22:48:19 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法使用.title()从带撇号的标题中获得正确的输出?例如:

"john's school".title() --> "John'S School"

我怎么才能得到正确的标题,"John's School"


Tags: 标题titlejohnschool办法
3条回答

这在一般情况下是很困难的,因为有些单撇号后面有一个大写字符是合法的,例如以“O”开头的爱尔兰名字。capwords()在很多情况下都可以工作,但忽略引号中的任何内容。capwords(“john's principal says,'no'”)不会返回您可能期望的结果。

>>> capwords("John's School")
"John's School"
>>> capwords("john's principal says,'no'")
"John's Principal Says,'no'"
>>> capwords("John O'brien's School")
"John O'brien's School"

更恼人的问题是,标题本身并不能产生正确的结果。例如,在美国用法英语中,冠词和介词通常不在标题或标题中大写。(芝加哥风格手册)。

>>> capwords("John clears school of spiders")
'John Clears School Of Spiders'
>>> "John clears school of spiders".title()
'John Clears School Of Spiders'

您可以轻松地安装titlecase module,这将对您更有用,并做您喜欢的事情,而无需使用大写字母。当然,仍然有很多边缘案例,但是您可以更进一步,而不必太担心个人编写的版本。

>>> titlecase("John clears school of spiders")
'John Clears School of Spiders'

我认为这对title()来说可能很棘手

让我们尝试一些不同的东西:

def titlize(s):
    b = []
    for temp in s.split(' '): b.append(temp.capitalize())
    return ' '.join(b)

titlize("john's school")

// You get : John's School

希望能有帮助!!

如果标题在一行中不包含几个空格字符(将被折叠),则可以使用string.capwords()代替:

>>> import string
>>> string.capwords("john's school")
"John's School"

编辑:正如Chris Morgan在下面正确地指出的,您可以通过在sep参数中指定" "来缓解空白折叠问题:

>>> string.capwords("john's    school", " ")
"John's    School"

相关问题 更多 >