Dav*_*542 37 python string uppercase
有没有办法.title()
用撇号从标题中获取正确的输出?例如:
"john's school".title() --> "John'S School"
Run Code Online (Sandbox Code Playgroud)
我如何在这里获得正确的标题"John's School"
?
Fré*_*idi 67
如果您的标题连续不包含多个空格字符(可以折叠),则可以使用string.capwords()代替:
>>> import string
>>> string.capwords("john's school")
"John's School"
Run Code Online (Sandbox Code Playgroud)
编辑:正如克里斯摩根在下面正确地说的那样,你可以通过" "
在sep
参数中指定来缓解空白崩溃问题:
>>> string.capwords("john's school", " ")
"John's School"
Run Code Online (Sandbox Code Playgroud)
Art*_*lor 11
在一般情况下这很困难,因为一些单个撇号合法地后跟一个大写字符,例如以"O"开头的爱尔兰名字.string.capwords()在很多情况下会起作用,但会忽略引号中的任何内容.string.capwords("约翰的校长说,'不'")不会返回你可能期望的结果.
>>> 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"
Run Code Online (Sandbox Code Playgroud)
一个更令人讨厌的问题是标题本身并没有产生适当的结果.例如,在美国使用英语中,文章和介词通常不会在标题或标题中大写.(芝加哥风格手册).
>>> capwords("John clears school of spiders")
'John Clears School Of Spiders'
>>> "John clears school of spiders".title()
'John Clears School Of Spiders'
Run Code Online (Sandbox Code Playgroud)
您可以轻松安装对您更有用的标题模块,并按照您的问题做您喜欢的事情.当然,仍有许多边缘情况,但你会更进一步,而不必过多担心个人写的版本.
>>> titlecase("John clears school of spiders")
'John Clears School of Spiders'
Run Code Online (Sandbox Code Playgroud)
我认为这可能很棘手 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
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.. !!