3
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?

taras
  • 3,579
  • 3
  • 26
  • 27
yuuske
  • 43
  • 1
  • 1
  • 4
  • 1
    The `string` module is a leftover from Python 1 and was made almost entirely obsolete when Python 2.0 introduced string methods. You almost *never* need to `import string`. I can think of only two exceptions: `maketrans()` (which I have used now and then) and the locale-dependent uppercase/lowercase stuff (which I have never used). – BoarGules May 21 '17 at 22:06
  • Thanks guys. Using `.title()` solved the problem. – yuuske May 22 '17 at 16:28
  • There's nothing obsolete about the `string` module. Some functions were deprecated in Python 2 in favor of methods on `str`. Those are gone in Python 3, so using the `string` module has nothing to do with those. See the docs: https://docs.python.org/3/library/string.html – Greg Price Jun 18 '21 at 19:28

2 Answers2

5

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.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • It turns out [string.capwords](https://docs.python.org/release/2.1/lib/module-string.html) has been a builtin forever, since 2.x. Rarely used. – smci May 21 '17 at 08:35
  • useful but will be fail where you do not wish to capitalise e.g. 123abc -> 123Abc. – CoDe Jul 31 '18 at 06:38
  • Capitalization is about text, not about arbitrary strings. To work with those you need to write a function that does what you want. – BoarGules Jul 31 '18 at 07:11
5

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.'
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153