Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

string - Python title() with apostrophes

Is there a way to use .title() to get the correct output from a title with apostrophes? For example:

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

How would I get the correct title here, "John's School" ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your titles do not contain several whitespace characters in a row (which would be collapsed), you can use string.capwords() instead:

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

EDIT: As Chris Morgan rightfully says below, you can alleviate the whitespace collapsing issue by specifying " " in the sep argument:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...