Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About Python capwords

from string import capwords

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

Why is it not equal to this? ↓

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

How can I do it?

like image 542
yuuske Avatar asked Feb 02 '26 15:02

yuuske


1 Answers

The documentation for string.capwords() says:

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.

If we do this step by step:

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

So you can see the double quotes are treated as being the part of the words, and so the following "t"s are not capitalised.

The str.title() method of strings is what you should use:

>>> s.title()
'"This Is Test", Please Tell Me.'
like image 79
snakecharmerb Avatar answered Feb 05 '26 07:02

snakecharmerb