Skip to main content
 首页 » 编程设计

python之关于 Python 首词

2025年05月04日9itcoder

from string import capwords 
 
capwords('\"this is test\", please tell me.') 
# output: '\"this Is Test\", Please Tell Me.' 
             ^ 

为什么不等于这个? ↓

'\"This Is Test\", Please Tell Me.' 
   ^ 

我该怎么做?

请您参考如下方法:

documentation对于 string.capwords() 说:

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

如果我们一步一步来:

>>> s = '\"this is test\", please tell me.' 
>>> split = s.split() 
>>> split 
['"this', 'is', 'test",', 'please', 'tell', 'me.'] 
>>> ' '.join(x.capitalize() for x in split) 
'"this Is Test", Please Tell Me.' 

因此您可以看到双引号被视为单词的一部分,因此后面的 "t" 没有大写。

str.title()字符串的方法是你应该使用的:

>>> s.title() 
'"This Is Test", Please Tell Me.'