关于 Python 个词
About Python capwords
from string import capwords
capwords('\"this is test\", please tell me.')
# output: '\"this Is Test\", Please Tell Me.'
^
为什么不等于这个? ↓
'\"This Is Test\", Please Tell Me.'
^
我该怎么做?
它不起作用,因为它很幼稚,并且被前导 "
混淆了,这使得它认为 "This
不是以字母开头。
改用内置字符串方法.title()
。
>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'
这可能是 capwords()
保留在 string
模块中但从未成为字符串方法的原因。
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"
没有大写。
你应该使用字符串的str.title()
方法:
>>> s.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.'
^
为什么不等于这个? ↓
'\"This Is Test\", Please Tell Me.'
^
我该怎么做?
它不起作用,因为它很幼稚,并且被前导 "
混淆了,这使得它认为 "This
不是以字母开头。
改用内置字符串方法.title()
。
>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'
这可能是 capwords()
保留在 string
模块中但从未成为字符串方法的原因。
string.capwords()
的 documentation 说:
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.
如果我们一步一步来:
>>> 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"
没有大写。
你应该使用字符串的str.title()
方法:
>>> s.title()
'"This Is Test", Please Tell Me.'