关于Python大写词

关于Python大写词,python,string,capitalize,Python,String,Capitalize,为什么不等于这个呢?↓ from string import capwords capwords('\"this is test\", please tell me.') # output: '\"this Is Test\", Please Tell Me.' ^ 我该怎么做呢?它不起作用,因为它太幼稚了,被前面的“搞糊涂了,它认为”这个不是以字母开头的 使用内置的字符串方法.title() '\"This Is Test\", Please Tell Me.'

为什么不等于这个呢?↓

from string import capwords

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

我该怎么做呢?

它不起作用,因为它太幼稚了,被前面的
搞糊涂了,它认为
”这个
不是以字母开头的

使用内置的字符串方法
.title()

'\"This Is Test\", Please Tell Me.'
   ^
这可能就是为什么
capwords()
仍保留在
string
模块中,但从未成为string方法的原因。

for
string.capwords()表示:

使用将参数拆分为单词,使用将每个单词大写,并使用将大写的单词连接起来。如果可选的第二个参数sep不存在或
None
,则空格字符将替换为一个空格,并删除前导和尾随空格,否则sep将用于拆分和连接单词

如果我们一步一步地这样做:

>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'
因此,您可以看到双引号被视为单词的一部分,因此下面的
“t”
s没有大写

字符串的方法是您应该使用的:

>>> 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.'

事实证明,自从2.x以来,它一直是一个内置的。很少使用。有用,但在不希望大写的情况下会失败,例如123abc->123abc。大写是关于文本,而不是任意字符串。要处理这些问题,您需要编写一个满足您需要的函数。我正要发布相同的内容:-d
string
模块是Python 1的遗留模块,在Python 2.0引入string方法时几乎完全过时。您几乎不需要
导入字符串
。我能想到的只有两个例外:
maketrans()
(我经常使用)和依赖于语言环境的大小写(我从未使用过)。谢谢大家。使用
.title()
解决了问题。
>>> s.title()
'"This Is Test", Please Tell Me.'