tan*_*nby 1 python string capitalize
from string import capwords
capwords('\"this is test\", please tell me.')
# output: '\"this Is Test\", Please Tell Me.'
^
Run Code Online (Sandbox Code Playgroud)
为什么不等于这个?↓
'\"This Is Test\", Please Tell Me.'
^
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
它不起作用,因为它是天真的,并被领导混淆",使它认为"This不以字母开头.
请改用内置字符串方法.title().
>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'
Run Code Online (Sandbox Code Playgroud)
这可能是为什么capwords()保留在string模块中但从未成为字符串方法的原因.
这 文档的string.capwords()说:
使用 将参数拆分为单词,使用将
str.split()每个单词大写str.capitalize(),并使用连接大写的单词str.join()。如果可选的第二个参数sep不存在或None,则空白字符的运行将替换为单个空格并删除前导和尾随空格,否则使用sep拆分和连接单词。
如果我们一步一步来:
>>> 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.'
Run Code Online (Sandbox Code Playgroud)
所以你可以看到双引号被视为单词的一部分,所以后面的"t"s 没有大写。
str.title()字符串的方法是你应该使用的:
>>> s.title()
'"This Is Test", Please Tell Me.'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6008 次 |
| 最近记录: |