关于Python capwords

2024-10-03 11:20:20 发布

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

from string import capwords

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

为什么不等于这个?下降

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

我该怎么做?


Tags: fromtestimportstringisthismeplease
2条回答

用于string.capwords()documentation表示:

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"不大写。

字符串的^{}方法应该使用:

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

它不起作用,因为它很幼稚,并且被前面的"混淆,这使得它认为"This不是以字母开头的。

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

>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'

这可能是capwords()保留在string模块中但从未成为字符串方法的原因。

相关问题 更多 >