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?
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?
It doesn't work because it is naive and is confused by the leading "
which makes it think that "This
does not begin with a letter.
Use the built-in string method .title()
instead.
>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'
This probably is the reason why capwords()
remains in the string
module but was never made a string method.
The documentation for string.capwords()
says:
Split the argument into words using
str.split()
, capitalize each word usingstr.capitalize()
, and join the capitalized words usingstr.join()
. If the optional second argument sep is absent orNone
, 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.'